POV
POV

Reputation: 12015

How to initialize @Input?

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[] = [];

Upvotes: 9

Views: 9498

Answers (2)

sagat
sagat

Reputation: 1406

For receiving the change do this:

ngOnChanges(changes: SimpleChanges) {
  if (changes.data.currentValue) {
    // Do Something with that data
  }
}

Upvotes: 3

Nicholas K
Nicholas K

Reputation: 15423

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.

Upvotes: 8

Related Questions