Angular 11中如何基于JSON对象实现复选框默认预选中功能
实现方案
你只需要修改app.component.ts中的ngOnInit生命周期钩子,完成预选中逻辑即可,原有HTML代码不需要调整:
- 先提取
compareJson中所有的id并去重,生成用于快速校验的id集合 - 遍历
checkboxesDataList的所有条目,为每个条目新增isChecked属性,id命中集合则设为true(预选中),否则设为false - 初始化完成后主动调用一次
changeSelection方法,同步初始状态下的选中数据,保证页面刚加载时提交功能也能正常运行
修改后完整代码
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() { // 提取所有需要预选中的id并去重 const targetIds = new Set(this.compareJson.map(item => item.id)); // 给所有复选框设置默认选中状态 this.checkboxesDataList = this.checkboxesDataList.map(item => ({ ...item, isChecked: targetIds.has(item.id) })); // 同步初始选中数据 this.changeSelection(); } 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); } }
修改完成后页面加载时,C001、C003对应的复选框会默认处于选中状态,原有勾选、提交逻辑不受影响。
内容的提问来源于stack exchange,提问作者uiankosh
相关产品推荐
相关产品推荐

