How to initialize @Input?
Asked Answered
K

2

9

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[] = [];
Kymric answered 5/8, 2019 at 9:54 Comment(1)
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.Tella
E
8

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.

Eustatius answered 5/8, 2019 at 9:56 Comment(9)
And what to do in ngOnChanges? This? this.data = changes; ?Kymric
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.Eustatius
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.Pero
Are you sure, that changes.currentValue; contains change of this.data? not rest variables?Kymric
Html is: [data]="response"Kymric
Yeah is ur response null? Or did u make sure there is data?Pero
Are you sure changes.data.currentValue?Kymric
Yes quite sure to receive the specific change for the inputPero
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 curiosityGrenier
P
3

For receiving the change do this:

ngOnChanges(changes: SimpleChanges) {
  if (changes.data.currentValue) {
    // Do Something with that data
  }
}
Pero answered 5/8, 2019 at 10:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.