angulartypescriptangular-lifecycle-hooks

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

Solution

  • 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.