Use NgOnChanges to see when an @Input is changing and bind it on a template give undefined. Use set instead

115 Views Asked by At

As per title my initial situation is that I am calling with 2 way data binding a funciton in my template

template.html

{{arePresent()}}

This basically check if I have a @INput variable length of type string []

component.ts

@Input inputVar: string[] | undefined
.
.
arePresent():boolean {
return this.inputVar?.length > 0;
}

For performance issue I read that is better to use a setter or use ngOnChnages. I tried this one

component.ts

variableToBindInTemplate :boolean;
@Input inputVar: string[] | undefined 
.
.
ngOnChanges(changes:SimpleChanges):void {
this.variableToBindInTemplate  =changes.inputVar?.currentValue?.length > 0;

and in my template of course I bind just the {{variableToBindInTemplate }}.

However the variable seems to come undefined.

Do you know how if is more convenient to use a setter or onPush change detection strategy? If yes how can I edit my component to use a setter?

1

There are 1 best solutions below

1
Shridhara M N On

This code will work.

variableToBindInTemplate :boolean;
@Input() inputVar: string[] | undefined 

ngOnChanges(changes:SimpleChanges):void {
this.variableToBindInTemplate = changes.inputVar?.currentValue?.length > 0;
}