-1

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?

mr_blond
  • 1,586
  • 2
  • 20
  • 52

2 Answers2

1

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

Guerric P
  • 30,447
  • 6
  • 48
  • 86
  • 1
    Your answer is 100% correct. Just to add something important from doc. The ngOnChanges() method is your first opportunity to access those input properties. Angular calls ngOnChanges() before ngOnInit(), but also many times after that. It only calls ngOnInit() once. – Panagiotis Bougioukos May 12 '21 at 16:22
1

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

Onur Özkır
  • 559
  • 3
  • 12