Angular NgFor 循环 2 个对象数组
Angular NgFor loop 2 arrays of objects
我想用 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>
这 2 个数组的长度相同,但我想将它们组合起来以显示单独的数据。
第一个数组有一个数据列表只是为了显示并且很好。
第二个数组 arrayCompetencias 我只想看看用户是否选中复选框并将其保存为 ngModel。
当试图获取 arrayCompetencias[i] 中的参数数据时。通过我检查了一个错误,该字段是 undefined,但我之前正在初始化它们。
第一个数组
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>
我没有改变,只是你的数据有问题。
You can check the code here
我想用 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>
这 2 个数组的长度相同,但我想将它们组合起来以显示单独的数据。 第一个数组有一个数据列表只是为了显示并且很好。 第二个数组 arrayCompetencias 我只想看看用户是否选中复选框并将其保存为 ngModel。
当试图获取 arrayCompetencias[i] 中的参数数据时。通过我检查了一个错误,该字段是 undefined,但我之前正在初始化它们。
第一个数组
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>
我没有改变,只是你的数据有问题。 You can check the code here