在Angular 2中,如果你使用@Input()装饰器来接收一个数组作为输入属性,并且没有设置默认值,当父组件没有传递该属性时,该数组将是未定义的。在这种情况下,你可以使用NgOnChanges生命周期钩子和简单的条件检查来处理这个问题。
下面是一个示例代码:
在子组件中,声明一个输入属性,并使用@Input()装饰器:
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'child-component',
template: `
{{ item }}
`
})
export class ChildComponent implements OnChanges {
@Input() items: any[];
ngOnChanges(changes: SimpleChanges): void {
if (changes['items'] && changes['items'].currentValue) {
this.items = changes['items'].currentValue;
}
}
}
在父组件中,使用子组件并传递一个数组:
import { Component } from '@angular/core';
@Component({
selector: 'parent-component',
template: `
`
})
export class ParentComponent {
myItems: any[];
constructor() {
// 设置myItems数组
this.myItems = ['Item 1', 'Item 2', 'Item 3'];
}
}
在这个例子中,当父组件没有传递items属性时,子组件的ngOnChanges方法会被调用。在ngOnChanges方法中,我们检查changes对象是否包含items属性,并且当前值不为null或undefined。如果满足条件,我们将当前值赋给子组件的items属性。
这样,在子组件的模板中,我们就可以安全地遍历并显示items数组的内容。