问题描述
我对 ViewContainer 和结构指令有疑问。
我有一个自定义结构指令 = 例如“permissionAccess”。
它从我的 NGRX 存储区中选择数据并寻找匹配的权限。 如果没有权限,它会清除 ViewContainer。如果它有权限,它会使用注入的 TemplateRef 重建 ViewContainer。 (这一切都很好 - 我已经用 Dom 元素、组件、视图进行了测试)
但是……如果任何 Dom 包含 "ngIf" 指令,则无法重建 ViewContainer。
有人知道为什么会这样吗??我不知道!
它甚至失败了 *ngIf=“true”
模板示例作品:
<div *cwbPermission=“'ADMIN'">
<p>test container</p>
<div>
<p>nested container1</p>
<div>
<p>nested container2</p>
</div>
</div>
</div>
模板示例失败:
<div *cwbPermission=“'ADMIN'">
<p>test container</p>
<div *ngIf=“true">
<p>nested container1</p>
<div>
<p>nested container2</p>
</div>
</div>
</div>
谁能给我解释一下??我不知道!
解决方法
所以,我不确定这是否是解决此问题的最佳方法,但看起来它对我有用。 在视图容器中创建模板后,我添加了一个 changeDetectorRef.detectChanges(),现在 UI 会按照我的预期更新。 目前没有发现任何问题。
/**
* Creates the template content
*/
showContent(): void {
this.viewContainer.remove();
this.viewContainer.createEmbeddedView(this.templateRef,this.context,0);
this.cdref.detectChanges();
}