使用结构指令时不显示 <ng-template>

not show <ng-template> when using structure directive

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

   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 为真时它不显示标签。有什么问题吗?

模板部分:

<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>