首页 > 解决方案 > Angular NgFor循环2个对象数组

问题描述

我想用 ngFor 遍历两个不同的数组并将它们显示在 html 中。

 <div class="form-check ml-5" *ngFor="let item of competencias.competencias; let i = index">
    <input class="form-check-input" type="checkbox" [value]="item.id [(ngModel)]="arrayCompetencias[i].checked"> 
    <label class="form-check-label">
       <strong> {{ item.id }} </strong>  : {{ item.descripcion}}
    </label>
   </div>   

这两个数组的长度相同,但我想将它们组合起来以显示单独的数据。第一个数组有一个要显示的数据列表,很好。第二个数组 arrayCompetencias 我只想看看用户是否选中复选框并将其保存为 ngModel。

当试图在 arrayCompetencias[i].checked 中获取参数数据时,我发现该字段未定义的错误,但我之前正在初始化它们。

第一个数组

competencias = [{id: string, descripcion: string}]

第二个数组

arrayCompetencias = [{checked: boolean, id: string}]
[(ngModel)]="arrayCompetencias[i].checked">  

我怎样才能只将此字段读入数组并根据用户检查设置

标签: htmlarraysangularngfor

解决方案


我修正了您的代码中的一些错别字并添加了一些编辑。

尝试使用此示例,它应该与您完美配合。

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  competencias = [{id: "1", description: "This is a description"}]
  arrayCompetencias = [{checked: true, id: "1"}]
}
<div *ngFor="let item of competencias; let i = index">
  <input type="checkbox" 
    [value]="item.id" 
    [checked]="arrayCompetencias[i].checked"
    (change)="arrayCompetencias[i].checked = !arrayCompetencias[i].checked">
  <label>
    <strong> {{ item.id }} </strong> : {{ item.description}}
  </label>
</div>

推荐阅读