2016-04-21 78 views
2

我有嵌套对象角2:使对象与嵌套对象到子组件

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; 
} 

然后,当我尝试访问模板中的对象属性时,我得到错误;

+0

在你的标记中是'child-compoennt'只是一个错字吗?你有什么组件定义看起来像? – james

+0

@james只是选择器,templateUrl&styleUrls属性 – neilhem

+0

你在孩子中如何以及在哪里访问它? –

回答

3

尝试在你的HTML中使用Elvis操作符:data?.nestedData?.title

您还应该将@Input data更改为@Input() data

+0

我已将视图添加到组件装饰器 – neilhem

+0

正确,我的不好,我的眼睛将其解析为URL。是使用猫王操作员的任何帮助? – Celebes

+0

我的不好,我在@Input()中修正了错字。所以,如果我像这样访问模板中的数据{{data | json}}没有错误。但是,如果我这样写{{data.nestedData}},我有错误'EXCEPTION:TypeError:无法读取[{{data.nestedData?.title}}中未定义的属性'nestedData'。猫王操作员不起作用。 – neilhem

0

您无法访问构造函数中的输入。他们设置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 
    } 
} 
+0

我不想在构造函数中访问输入数据,我试图在视图中访问它 – neilhem

+1

很高兴知道,但你仍然不显示如何。那么你可能需要使用安全导航操作符。 '{{data?.nestedData?.title}}'或'=“data?.nestedData?.title'' –