Why is value of @Input() null in Angular?

Why is value of @Input() null in Angular?

I have an Input variable in my component that looks like this:

@Input() Id:  string;

In my template, I'm displaying the Id and it has a value:

Id == {{ Id }}

But in the ngOnInit in the TypeScript when I try to print the Id, it's null

ngOnInit(): void {
console.log('Id=' + this.Id);

What am I doing wrong? Am I trying to access it too early? Is there something I can do in order to get the actual value in the ngOnInit() ?

Answer

OnInit is called (only once) when the component is constructing.

According from here,

Keep in mind that a directive's data-bound input properties are not set until after construction.

Insead, you should use OnChanges hook.

ngOnChanges(changes: SimpleChanges): void {
  // Or
  // if (this.Id)
  if (changes["Id"])
    console.log('Id=' + this.Id);
}

Side note, when there is change(s) of input properties, the OnChanges hook will be triggered and hence you may get the message printed in console multiple time.

Otherwise, you can use the hook such as AfterViewInit based on this Lifecycle event sequence table to ensure the input properties' value(s) have been provided.

Enjoyed this question?

Check out more content on our blog or follow us on social media.

Browse more questions