Search code examples
javascriptangularinputbindingngoninit

How to handle undefined when passing data with Input in Angular?


A component colled with passing value with Input():

<app-available-modal [good]="'test'"></app-available-modal>

The component looks like:

@Component({
  selector: 'app-available-modal',
  templateUrl: './available-modal.component.html',
  styleUrls: ['./available-modal.component.scss']
})
export class AvailableModalComponent implements OnInit {
  @Input() good: TyreGoodModelTemp;

  constructor() {
    console.log(this.good);
  }

  ngOnInit(): void {
    console.log(this.good);
  }
}

I expect "test" and "test" output in the console.

And the console.log from ngOnInit() prints "test". But console.log from constructor() prints "undefined".

Why does it happen and how do I handle it?


Solution

  • In Angular the constructor function of a component class is being used for service injection only. Everything that is related to rendering and @Input resolving has to be handled in Angular's lifecycle hooks like ngOnInit and ngOnChanges