当向嵌套数组中添加对象时,我们需要确保所有嵌套数组和对象已经被初始化。如果未初始化,试图向其添加对象时将会抛出“Cannot read properties of undefined”错误。
下面是一个示例,演示如何向嵌套数组中添加对象,并避免出现错误:
在组件中定义数组,并在每个嵌套对象中初始化数组:
export class MyComponent {
myNestedArray: { nestedArray: any[] }[] = [
{ nestedArray: [] },
{ nestedArray: [] }
];
}
在模板中使用*ngFor循环来遍历嵌套对象和数组。使用ngModel绑定向每个对象中的数组添加新元素:
{{ item }}
添加一个添加项目方法,该方法将新项目添加到嵌套数组中:
addItem(nestedObj) {
nestedObj.nestedArray.push(this.newItem);
}
这将确保我们可以向嵌套数组中添加项目,而不会出现“Cannot read properties of undefined”错误。
上一篇:Angular解码请求URL