如何在另一个 *Ngfor 中使用 *Ngfor

How to use *Ngfor in an other *Ngfor

我正在尝试为数组的每个元素创建一个复选框 "lesCriteres"。 然后我希望检查每个复选框的值是否在 table "actif.lesCriteresActifs"

这是我想要的代码,但它无法正常工作

<div class="checkbox-inline" *ngFor="let l of lesCriteres">
    <div *ngFor="let a of actif.lesCriteresActifs">
        <label></label>
        <input type="checkbox" (change)="onChangeEvent(l.code, $event.target.checked)" [checked]="a.critere.code==l.code"> {{l.code}}<br>
     </div>
</div>

型号

actif 模型

import {TypeActif} from './model.type-actif';
import {CritereActif} from './model.critere-actif';

export class Actif{
  ref: string;
  nom: string = '';
  type_actif: TypeActif = new TypeActif();
  lesCriteresActifs: Array<CritereActif> = new Array<CritereActif>();
}

CritereActif 模型

import {Actif} from './model.actif';
import {LesCriteres} from './model.les-criteres';
import {LesValeurs} from './model.les-valeurs';

export class CritereActif{
  id: number;
  actif: Actif = new Actif();
  critere: LesCriteres = new LesCriteres();
  valeur: LesValeurs = new LesValeurs();
}

LesCriteres 模型

export class LesCriteres{
  code: string = null;
  nom: string = '';
}

结果

我在执行我的代码时有这个:

但我不想要这样的东西:

这应该有效(使用 includes() 方法,无需额外的 *ngFor):

<div class="checkbox-inline" *ngFor="let l of lesCriteres">
        <label></label>
        <input type="checkbox" (change)="onChangeEvent(l.code, $event.target.checked)" [checked]="actif.lesCriteresActifs.includes(l)"> {{l.code}}<br>
</div>

关于包含方法:https://www.w3schools.com/jsref/jsref_includes_array.asp

编辑:

想到这个解决方案。 在组件的 .ts 文件中,在 class 内声明一个函数:

containsCode = (code) => {
    for (let a of this.actif.lesCriteresActifs) {
        if (a.critere.code === code) {
            return true
        }
    }
    return false

然后在 .html 文件中:

<div class="checkbox-inline" *ngFor="let l of lesCriteres">
        <label></label>
        <input type="checkbox" (change)="onChangeEvent(l.code, $event.target.checked)" [checked]="containsCode(l.code)"> {{l.code}}<br>
</div>