我想操纵传递给子组件的数据,但我无法从组件中访问该变量。我似乎只能从模板中获取数据。为什么数据变量未在组件内定义,而不是模板?
父组件模板:
//messageReceived is an array of objects
<app-data-table [data]='messageReceived'>
子组件
@Input() data: any;
constructor() {console.log(this.data)} /*This DOESN'T work. this.data is undefined
ngOnInit() {
console.log(this.data) /*empty object*/
}
子组件模板:
{{data | json }} <!--This DOES work-->
答案 0 :(得分:2)
因为当组件仅启动启动但输入未绑定时,您在构造函数中使用它。你应该使用
ngOnInit() {
conosle.log(this.data)
}
或
ngOnChanges(changes) {
console.log(changes.data);
if (changes.data) {
this.data = this.data.currentValue;
console.log(this.data)
}
}
答案 1 :(得分:0)
@alexKhymenko 的回答很好,但在许多情况下,直接使用 setter 操作输入会更好/更容易,如下所示:
@Input() set data(myData: any) {
this.manipulatedData = { ...myData, myProp: true };
}
manipulatedData: any
constructor() {
console.log(this.manipulatedData) // logs undefined always
console.log(this.data) // logs undefined always
}
ngOnInit() {
console.log(this.manipulatedData) // logs { preExistingProp: 'something', myProp: true }
console.log(this.data) // oddly, also logs undefined
}