如何实现仅当Observable条目少于9个时显示Mat-Chip列表?
解决mat-chip仅在Observable数组条目数少于9时显示的问题
你之前的写法有两个问题:
- 拼写错误:
lenght应该是length - 重复使用
async管道:已经通过*ngIf="selectedAttributes$ | async as attributes"把Observable解析成了本地变量attributes,没必要再对原Observable执行async,这会引发重复订阅,也会导致逻辑不生效
根据你的需求,提供两种可行方案:
方案一:仅当数组长度<9时渲染整个chip列表
如果希望整个mat-chip-list都只在数组条目数少于9时显示,直接在mat-chip-list的*ngIf里合并条件:
<mat-chip-list *ngIf="(selectedAttributes$ | async) as attributes && attributes.length < 9"> <div *ngFor="let attribute of attributes"> <mat-chip *ngIf="attribute.isSelected">{{attribute.label}} <button matChipRemove (click)="onChipClose(attribute.label)"> <mat-icon>cancel</mat-icon> </button> </mat-chip> </div> </mat-chip-list>
方案二:始终渲染chip列表,但仅当数组长度<9时显示选中的chip
如果需要mat-chip-list一直存在,但只有数组条目数少于9时才显示对应的mat-chip,把判断条件加到mat-chip的*ngIf中:
<mat-chip-list *ngIf="selectedAttributes$ | async as attributes"> <div *ngFor="let attribute of attributes"> <mat-chip *ngIf="attribute.isSelected && attributes.length < 9">{{attribute.label}} <button matChipRemove (click)="onChipClose(attribute.label)"> <mat-icon>cancel</mat-icon> </button> </mat-chip> </div> </mat-chip-list>
内容的提问来源于stack exchange,提问作者user15339638
相关产品推荐
相关产品推荐

