【问题标题】:not show <ng-template> when using structure directive使用结构指令时不显示 <ng-template>
【发布时间】:2018-12-21 09:29:55
【问题描述】:

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

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

【问题讨论】:

    标签: javascript angular typescript angular6 angular2-directives


    【解决方案1】:

    模板部分:

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

    扩展为:

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

    您的指令呈现位于&lt;ng-template [appUser]="op.id"&gt; 中的所有内容。我们可以看到它被包裹在另一个 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>
    

    【讨论】:

    • 它的工作,但是当我使用 &lt;ng-conteiner&gt; 时它告诉我 Static injection Error 。为什么要显示这个错误??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    • 1970-01-01
    • 2021-08-04
    • 2021-05-15
    • 2019-10-04
    相关资源
    最近更新 更多