I am wondering if the below code is fine in terms of performance.
in html
<button [disabled]="isDisabled()">btn</button>
in ts (component)
isDisabled(): boolean {
//...some loop calculation
console.log('run isDisabled');
return result;
}
The isDisabled method is executed all the time even you just scroll down the web browoser.
In the official Angular
A property name or method call should be the norm.
I can see that calling method is allowed but I feel it's kind of wasting specially there is a loop logic.
Can I keep using calling a method in [disabled] attribute in html or is there better way ?
Thanks.
I don't recommend to use function calls inside your html, because the function is called very often, like you said. In your case you can simply use a pipe or a boolean flag, which you set inside your component/service.
The pipe solution can look like this:
disabled.pipe.ts
@Pipe({name: 'disabled'})
export class DisablePipe implements PipeTransform {
// Maybe you need additional params
transform(arr: any[]) {
// Do you loop over the array
return result;
}
}
And in you html:
<button [disabled]="yourArray | disabled">btn</button>
It is okay but not good.
Consider you have 500 iterations in your for loop, on any change detection this might run. Usually the best way is to use Observable API do declare dependent values, since you can then use the async pipe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With