2

I would like to manipulate data that is passed into a child component but I can't access that variable from within the component. I can only seem to get the data from the template. Why is the data variable undefined from within the component but not the template?

Parent component template:

//messageReceived is an array of objects
 <app-data-table [data]='messageReceived'>

Child component

 @Input() data: any;
 constructor() {console.log(this.data)} /*This DOESN'T work. this.data is undefined
 ngOnInit() {
  console.log(this.data) /*empty object*/
 }

Child component template:

{{data | json }} <!--This DOES work--> 
3
  • 1
    You're looking for ngOnChanges/ngOnInit Commented Sep 18, 2017 at 19:37
  • @yurzui I get an empty object for ngOnChanges/ngOnInit Commented Sep 18, 2017 at 19:40
  • 1
    Are you getting data from server? Did you try ngOnChanges hook? Commented Sep 18, 2017 at 19:43

2 Answers 2

3

Cause you are using it in the constructor when component only starts initiating but inputs are not binded. You should use

ngOnInit() {
 conosle.log(this.data)
}

or

 ngOnChanges(changes) {
     console.log(changes.data);
    if (changes.data) {
        this.data = this.data.currentValue;
        console.log(this.data)
     }
   }
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! with the exception of this.data.currentValue. It should only be this.data in my case.
0

@alexKhymenko's answer is good, but in many cases it's better/easier to just manipulate the input directly with a setter, as follows:

@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

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.