html - 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">
我怎样才能只将此字段读入数组并根据用户检查设置
解决方案
我修正了您的代码中的一些错别字并添加了一些编辑。
尝试使用此示例,它应该与您完美配合。
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>
推荐阅读
- javascript - 如何从网络摄像头捕获图片并将其存储在 Django 的 ImageField 或 FileField 中?
- java - 元素的 Selenium Nullpointer 异常
- tabulator - Persistent Config 不允许在隐藏列时重新渲染表
- python - 如果需要 numpy 和 cv2 预处理,则从目录加载图像的最佳方法
- java - Java远程调试“读取超时”问题
- vb.net - 尝试 ping 时的 vb.net System.ArgumentOutOfRangeException
- php - Spatie Translation Loader - 缺少完全匹配但存在前缀键时传递的翻译不正确
- java - 取消选择 JTable 行时行数据消失
- azure - Azur Key Vault - 在 Azure 应用服务中使用 Azure KeyVault 后出现 CORS 错误
- url - 如何为其他用户生成注册网址