Reputation:
Is it good/bad practice to disable an Angular button with a component method? Specifically, Would this be a performance issue in Angular? It seems like Angular would have to continuously calculate.
Is it better to use a static variable (eg this.productDisable: boolean), and just let it calculate at certain times?
isProductSaveDisabled() {
if (this.productsSelected == null || this.productsSelected ?.length === 0) {
return true;
} else {
return false;
}
}
HTML:
<button mat-raised-button [disabled]="isProductSaveDisabled()" (click)="saveAll()">
Save Product
</button>
Curious reading loot of tutorials and articles using class methods, etc
Upvotes: 1
Views: 786
Reputation: 21648
This is the sort of question you will get asked in job interviews and it can cost you the job so don't put a function call in the template.
The best answer would be to use a pipe
@Pipe({
name: 'emptyArray'
})
export class EmptyArrayPipe implements PipeTransform {
transform(array: any[]): boolean {
return !!array || array.length === 0;
}
}
and use it
[disabled]="productsSelected | emptyArray"
This will only trigger change detection to rerun the logic if productsSelected changes.
If you go for a lot of Angular tech interviews you are likely to encounter this kind of scenario.
Upvotes: 5
Reputation: 24965
With the way you have written it, there is not going to be any noticible performance difference between the non-function version and the function version. Both pieces of code will be executed the same number of times, any time change detection needs to re-evaluate.
What is of concern though is that the component method approach not only gives you a little more separation of concerns with the view logic and the controller logic, but it also increases the readibility of the code and introduces a chance for self documentation with the function name.
Upvotes: -1