I have a parent component which is getting data from a server through a service. I need some of this data to be passed to the Child component.
I\'ve been trying to p
you can use ngOnChanges to get data like below,
ngOnChanges() {
if(!!childData){
console.log(childData);
}
}
OnChanges
Angular calls its ngOnChanges method whenever it detects changes to input properties of the component (or directive).
Read more about it here.
Update
ngOnChanges will only fire if you change entire object, if you want to just update property of the bound object not entire object you have two options,
either bind the property directly in the template, make sure to use ? like {{childData?.propertyname}}
or you can create a get property depending upon childdata object,
get prop2(){
return this.childData.prop2;
}
Copmlete Example,
import { Component, Input } from '@angular/core';
@Component({
selector: 'my-app',
template: `Hello {{name}}
`
})
export class AppComponent {
name = 'Angular';
childData = {};
constructor(){
// set childdata after 2 second
setTimeout(() => {
this.childData = {
prop1 : 'value of prop1',
prop2 : 'value of prop2'
}
}, 2000)
}
}
@Component({
selector: 'child-component',
template: `
prop1 : {{childData?.prop1}}
prop2 : {{prop2}}
`
})
export class ChildComponent {
@Input() childData: {prop1: string, prop2: string};
get prop2(){
return this.childData.prop2;
}
}
Here is the Plunker!
Hope this helps!!