【发布时间】:2021-08-26 01:40:33
【问题描述】:
我有 2 个对象数组,一个 compareJson 和其他 checkboxesDataList ,所以在选择复选框时,我正在比较两个 json 的 id 并在 console.log(matches) 中获取 checkboxesDataList 的过滤值;我在这里得到了正确的值。现在我想在页面加载时根据 id 预先比较 json 并预先选择复选框。例如 C001 和 C003 在两个 json 中都很常见,因此只有来自 checkboxesDataList 的数据会被预先选择。这是代码
https://stackblitz.com/edit/angular-fst6jp?file=src%2Fapp%2Fapp.component.ts,
app.component.html
<hello name="{{ name }}"></hello>
<p>
Start editing to see some magic happen :)
</p>
<ul class="checkbox-items">
<li *ngFor="let item of checkboxesDataList">
<input type="checkbox" [(ngModel)]="item.isChecked" (change)="changeSelection()">{{item.label}}
</li>
</ul>
<button (click)="submit()">Submit</button>
<div *ngFor="let item of compareJson">Item listed - {{item.details}}</div>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular';
selectedItemsList: any[] = [];
checkedIDs: any[] = [];
compareJson = [
{
id: 'C001',
details: 'Photography details'
},
{
id: 'C001',
details: 'Writing details'
},
{
id: 'C003',
details: 'Painting Details'
}
];
checkboxesDataList = [
{
id: 'C001',
label: 'Photography'
},
{
id: 'C002',
label: 'Writing'
},
{
id: 'C003',
label: 'Painting'
}
];
ngOnInit() {}
changeSelection() {
this.checkedIDs = [];
this.selectedItemsList = this.checkboxesDataList.filter((value, index) => {
return value.isChecked;
});
console.log(this.selectedItemsList);
let i;
for (i = 0; i < this.selectedItemsList.length; i++) {
console.log(this.selectedItemsList[i].id);
this.checkedIDs.push(this.selectedItemsList[i].id);
}
const matches = this.compareJson.filter(object =>
this.checkedIDs.includes(object.id)
);
console.log(matches);
}
submit() {
const matches = this.compareJson.filter(object =>
this.checkedIDs.includes(object.id)
);
console.log(matches);
}
}
【问题讨论】:
-
您是否询问如何为
checkboxesDataList中的每个项目预填充isChecked?另外,相关:stackoverflow.com/questions/43892383/… -
是的,你是对的
标签: javascript angular