代码之家  ›  专栏  ›  技术社区  ›  Gargoyle

*角度5中<tr>元素上的ngFor和*ngIf

  •  2
  • Gargoyle  · 技术社区  · 7 年前

    在我的Angular 5应用程序中,我正在循环创建 tr 元素:

    <tr *ngFor="let element of elements">
    

    但我只想在满足某些条件的情况下显示行。我知道我不能用 *ngFor *ngIf 但我不知道该怎么处理这件事。

    我看到一篇帖子说在tr中添加一个模板 [ngIf] 但这似乎不再是有效的语法。如果我这样尝试:

    <tr *ngFor="let element of elements">
        <template [ngIf]="element.checked || showUnchecked">
    

    然后我得到运行时错误。

    AppComponent。html:14错误错误:StaticInjectorError(AppModule)[NgIf->TemplateRef]:
    StaticInjectorError(平台:核心)[NgIf->TemplateRef]:
    NullInjectorError:没有TemplateRef的提供程序!

    2 回复  |  直到 7 年前
        1
  •  1
  •   gmazzotti    7 年前

    创建一个getter,返回已筛选的属性元素。类似于

    get filteredElements() {
        if( this.showUnchecked ) {
            return this.elements;
        } else {
            return this.elements.filter( () => { return this.checked; } );
        }
    }
    
        2
  •  1
  •   Mark Rotteveel    6 年前

    ng容器可以代替模板工作

    <table><tr *ngFor="let element of elements">
    <ng-container *ngIf="element.checked || showUnchecked">
      <td></td>
      <td></td>
    </ng-container>
    </tr>
    <table>