首页 > 解决方案 > 不显示使用结构指令时

问题描述

我创建了这个指令来显示或隐藏标签。

   Directive({
  selector: '[appUser]'
})
export class UserDirective {

  RoleId:Subscription | null=null;
  op:boolean;
  _roleId:number;
  opo:ValidateUR;

  constructor(private optService:OptionsService
    ,private logserve:LoginService,
    private templateRef: TemplateRef<any>,
    private viewContainerRef: ViewContainerRef) { 
     this.opo=this.optService.initialValidateUR();
      this.RoleId=this.logserve._roleId$.subscribe((rId)=>{
      this._roleId=rId;
    })
  }

  @Input('appUser') set ngRoleValidate(oId:number)
  {
    this.opo.optionId=oId;
    this.optService.ValidateUser(this.opo).subscribe((rid)=>{

      if(rid==true)
      {
        console.log('in true')
          this.viewContainerRef.createEmbeddedView(this.templateRef);
      }else{
          this.viewContainerRef.clear();
      }
    })
  }
}

这是html代码:

   <li *ngFor="let op of optionList">
        <ng-template *appUser="op.id">
              <!-- <fa-icon [icon]="op.icon"></fa-icon>  -->
              <label  (click)='this[op.routeFunctionName]()'>{{op.optionName}}</label>
        </ng-template>
    </li>

现在我需要什么时候rid为真,它显示标签,当它为假时隐藏标签,但什么时候rid为真,它不显示标签。有什么问题 ?

标签: javascriptangulartypescriptangular6angular2-directives

解决方案


模板部分:

<ng-template *appUser="op.id">

扩展为:

<ng-template [appUser]="op.id">
  <ng-template>

您的指令呈现位于内部的所有内容<ng-template [appUser]="op.id">。我们可以看到它被包裹在另一个ng-template不创建嵌入视图的情况下无法渲染的内容中。

为了正确渲染它,我将使用ng-container而不是ng-template

<ng-container *appUser="op.id">
  <!-- <fa-icon [icon]="op.icon"></fa-icon>  -->
  <label  (click)='this[op.routeFunctionName]()'>{{op.optionName}}</label>
</ng-container>

另一种方法是使用扩展版本:

<ng-template [appUser]="op.id">
  <!-- <fa-icon [icon]="op.icon"></fa-icon>  -->
  <label  (click)='this[op.routeFunctionName]()'>{{op.optionName}}</label>
</ng-template>

推荐阅读