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

1.3k Views Asked by At

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?

2

There are 2 best solutions below

1
On BEST ANSWER

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

0
On

Don't try to access @Input()s in the constructor, do it in the ngOnInit life-cycle hook. The constructor has almost nothing to do with the Angular application life-cycle.

For more information : #8015757