8

I tried to do that like:

  @Input() data: any[] = [];

Inside ngOnInit I see undefined:

 ngOnInit() {
    console.log(this.data);
  }

So, below in code I get error, when I try to get length: return this.data.length;

Because it is undefined.

Why initialization does not work by default?

@Input() data: any[] = [];
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
POV
  • 11,293
  • 34
  • 107
  • 201
  • This does work by default and you should be seeing a [] in the log. The problem is that the value in your parent component is most likely undefined when passed to child component for a first time. – Dino Aug 05 '19 at 10:28

2 Answers2

7

You need to use the OnChanges angular directive.

export class AppComponent implements OnChanges {
    ...

    ngOnChanges(changes: SimpleChanges) {
        this.data = changes.data.currentValue;   // fetch the current value
        console.log(this.data);
    }

    ...
}

More on this directive can be found in the docs.

Respond when Angular (re)sets data-bound input properties. The method receives a SimpleChanges object of current and previous property values.

Called before ngOnInit() and whenever one or more data-bound input properties change.

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
  • And what to do in `ngOnChanges`? This? `this.data = changes;` ? – POV Aug 05 '19 at 09:58
  • you can get the new value by `this.data = changes.currentValue`. You can do a console.log on the `changes` object to see its other attributes. – Nicholas K Aug 05 '19 at 10:00
  • Mate could u show us ur html code and the component that is passing data to ur childcomponent ? You can receive changes like that changes.data.currentValue. – sagat Aug 05 '19 at 10:05
  • Are you sure, that `changes.currentValue; ` contains change of `this.data`? not rest variables? – POV Aug 05 '19 at 10:05
  • Html is: `[data]="response"` – POV Aug 05 '19 at 10:07
  • 1
    Yeah is ur response null? Or did u make sure there is data? – sagat Aug 05 '19 at 10:07
  • Are you sure `changes.data.currentValue`? – POV Aug 05 '19 at 10:07
  • Yes quite sure to receive the specific change for the input – sagat Aug 05 '19 at 10:09
  • I'm pretty new to Angular and I'm wondering shouldn't this also be correct with rxjs and passing an observable? Or we should stick to built in Angular methods? Just out of curiosity – Paweł Sosnowski Jun 07 '23 at 08:49
3

For receiving the change do this:

ngOnChanges(changes: SimpleChanges) {
  if (changes.data.currentValue) {
    // Do Something with that data
  }
}
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
sagat
  • 1,351
  • 12
  • 15