【问题标题】:How to use *Ngfor in an other *Ngfor如何在另一个 *Ngfor 中使用 *Ngfor
【发布时间】:2019-08-28 11:23:34
【问题描述】:

我正在尝试为数组“lesCriteres”的每个元素创建一个复选框。 然后我希望检查每个复选框的值是否在表“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 = '';
}

结果

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

但我不想要这样的东西:

【问题讨论】:

  • 我不明白你为什么使用索引。一旦你写了“let a of actif.lesCriteresActifs; let i=index”,那么稍后在代码中使用的 actif.lesCriteresActifs[i] 与“a”是一样的! :D 很抱歉,我还是不太明白你想要达到什么目的。
  • 你说得对,我编辑了它
  • 每个复选框都有一个值。我想看看它的值是否存在于 a.critre 中。如果它存在,我检查它!对不起,也许是因为我的英语:(
  • 现在我知道你想要实现什么了。请检查我编辑的答案。
  • 有效!!!谢谢大家:)

标签: html angular checkbox ngfor


【解决方案1】:

这应该可以工作(使用 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 文件中,在类中声明一个函数:

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> 

【讨论】:

  • 比较不是在 actif.lesCriteresActifs 的元素和 lesCriteres 的元素之间,而是在 lesCriteresActifs.critere 的元素和 lesCriteres 的元素之间进行比较,这就是为什么我需要 lesCriteresActifs 的元素的索引跨度>
  • 我不确定我是否理解正确。然后在你的代码中,你不想要元素“l”的索引,而不是元素“a”的索引吗?
  • 浏览一下您的一些数据会有所帮助。
  • 是的!我英语不好!!等等,我会编辑我的帖子,以便您更好地理解
  • 你现在明白了吗?
猜你喜欢
  • 2021-08-12
  • 1970-01-01
  • 2018-08-22
  • 2020-05-02
  • 2019-03-30
  • 2018-09-20
  • 1970-01-01
  • 2017-01-08
  • 1970-01-01
相关资源
最近更新 更多