首页 > 解决方案 > 使用 *ngFor 迭代时检查值是否存在 - Angular 10

问题描述

我通过迭代两个数组来填充mat-select :

<mat-select>
     <mat-optgroup *ngFor="let group of groups; trackBy: trackGroup" [label]="group.name">
       <ng-container *ngFor="let question of group.questions; trackBy: trackQuestion">
         <mat-option [value]="question._id">
            {{question.title}}
         </mat-option>
       </ng-container>
   </mat-optgroup>
</mat-select>

我想检查给定的问题 id 是否在列表中,而无需在控制器 ts 文件中重新进行迭代。如果它不存在,我想将一个类应用于垫选择之外的 div。像这样的东西:

<div [ngClass]="{'warning': !exists}">
    <mat-select>
        ...
    </mat-select>
</div>

我怎样才能做到这一点?我以为我可以在 trackBy 函数中做到这一点,但似乎组件变量尚未定义。

标签: angularngfor

解决方案


推荐阅读