2017-09-01 53 views
0

我有一个列表的列表,我想基于属性值角4 - 显示/隐藏在ngFor指令元素

<md-list *ngFor="let el of data"> 
    <md-list-item *ngFor="let item of el.items" > 
     <h4 mdSubhead]er>{{item.name}}</h4> 
    </md-list-item>h4 
    </md-list> 

我与*ngIf试图隐藏/显示内部列表,但只有Angular4许可证一个元素的模板绑定。

我该如何实现这个beavior?

+0

什么是显示/隐藏条件?你可以使用'ng-container'或者尝试'[hidden]'属性。 – briosheje

+1

[\ * ngIf和\ * ngFor在相同的元素上导致错误]的可能重复(https://stackoverflow.com/questions/34657821/ngif-and-ngfor-on-same-element-causing-error) –

回答

3

您可以通过添加额外的div与条件或ng-container这将是最好的角度

<md-list *ngFor="let el of data"> 
    <ng-container *ngIf="el.something"> 
    <md-list-item *ngFor="let item of el.items" > 
     <h4 mdSubheader>{{item.name}}</h4> 
    </md-list-item> 
    </ng-container> 
</md-list> 
2

使用ng-container(无需额外的元素的)只是做并在相同的使用*ngIfhide/show DOM有条件。

<md-list *ngFor="let el of data"> 
    <ng-container *ngIf="el.show"> 
    <md-list-item *ngFor="let item of el.items" > 
     <h4 mdSubhead]er>{{item.name}}</h4> 
    </md-list-item> 
    </ng-container> 
</md-list> 
+1

Cleverest解决方案因为'ng-container'不会被添加到DOM。这是正确的方法。 – briosheje

+0

ng-container> ng-template>这种情况下的DOM元素 –

0

这里提到使用<ng-container><ng-container> to the rescue

<md-list *ngFor="let el of data"> 
    <ng-container *ngIf="your-condition-here"> 
     <md-list-item *ngFor="let item of el.items" > 
      <h4 mdSubhead]er>{{item.name}}</h4> 
     </md-list-item> 
    </ng-container> 
</md-list> 
1

我认为最好的办法可能是之前得到的数据,然后删除不需要的项目,并通过剩余的列表进行迭代。但如果真的需要模板,那么你可以使用ng-template和long * ngFor版本,所以如下所示:

<ng-template ngFor let-el [ngForOf]="data" let-i="index"> 
<md-list #el> 
<ng-template ngFor let-item [ngForOf]="el.items" let-i="index"> 
    <md-list-item #item> 
    </md-list-item>h4 
    </ng-template> 
</md-list> 
</ng-template> 
+1

只需要添加到John Snow,您就可以添加一个过滤器来过滤掉你不想要的东西。 –