Angular中按传入索引为对象数组元素添加子数组的实现方法
实现逻辑
- 先校验传入的index是否在data数组的合法范围内,避免数组越界报错
- 取出index对应的数组元素,判断是否存在
Address子数组,不存在则先初始化空数组 - 将当前组件中存储的城市值追加到
Address数组即可
完整代码示例
首先组件中需要先定义存储当前城市的变量(可根据实际业务绑定表单输入值),再修改save方法:
import { Component } from '@angular/core'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html', styleUrls: ['./your-component.component.css'] }) export class YourComponent { // 存储当前要添加的城市值,可通过ngModel绑定到页面输入框,或按业务逻辑赋值 currentCity: string = ''; data = [ { "name":"Rosy" }, { "name":"julia" } ]; save(index: number): void { // 校验索引合法性 if (index < 0 || index >= this.data.length) { return; } const target = this.data[index]; // 不存在Address数组则初始化 if (!Array.isArray(target['Address'])) { target['Address'] = []; } // 追加新城市 target['Address'].push(this.currentCity); // 若组件使用ChangeDetectionStrategy.OnPush变更检测策略,需额外加以下行触发视图更新 // this.cdr.markForCheck(); } }
拓展说明
如果需要存储的不是城市字符串,而是包含更多属性的对象,修改push逻辑即可,示例:
target['Address'].push({ city: this.currentCity, createTime: new Date().toISOString() });
内容的提问来源于stack exchange,提问作者Rosy
相关产品推荐
相关产品推荐

