Angular 2:将带有嵌套对象的对象传递给子组件
Angular 2: passing object with nested object to child component
我有嵌套对象
data: {
nestedData: {
title: 'string'
}
};
我通过 属性
将此数据传递给子组件
<child-component [data]="data"></child-component>
子组件代码:
import {Component, Input} from 'angular2/core';
@Component({
selector: 'cp-header',
template: '<div>{{ data.nestedData.nestedData }}</div>',
styleUrls: ['app/header/header.component.css']
})
export class ChildComponent {
@Input() data;
}
然后当我尝试访问模板中的对象 属性 时出现错误;
您无法访问构造函数中的输入。它们是在调用 ngOnInit
之前设置的:
export class ChildComponent {
@Input data;
constructor() {
console.log(this.data); // here it prints `null`
}
ngOnInit() {
console.log(this.data); // here it prints the actual value
}
}
尝试在 HTML 中使用 elvis 运算符:data?.nestedData?.title
。
您还应该将 @Input data
更改为 @Input() data
。
我有嵌套对象
data: {
nestedData: {
title: 'string'
}
};
我通过 属性
将此数据传递给子组件<child-component [data]="data"></child-component>
子组件代码:
import {Component, Input} from 'angular2/core';
@Component({
selector: 'cp-header',
template: '<div>{{ data.nestedData.nestedData }}</div>',
styleUrls: ['app/header/header.component.css']
})
export class ChildComponent {
@Input() data;
}
然后当我尝试访问模板中的对象 属性 时出现错误;
您无法访问构造函数中的输入。它们是在调用 ngOnInit
之前设置的:
export class ChildComponent {
@Input data;
constructor() {
console.log(this.data); // here it prints `null`
}
ngOnInit() {
console.log(this.data); // here it prints the actual value
}
}
尝试在 HTML 中使用 elvis 运算符:data?.nestedData?.title
。
您还应该将 @Input data
更改为 @Input() data
。