Reputation: 482
Does the a method is called multiple in *ngIf which is inside a *ngFor I have below code sample.
HTML Code
<div *ngFor="let item of groups">
<div class="headerBar" *ngIf="showHeader(item)">
<h3>Hello to the Board</h3>
</div>
</div>
//Typescript Code
showHeader(item){
let show = true;
if(item.group === 'invalid' || item.group === 'unkown' || item.group === 'invisible'){
show = false;
}
return show;
}
Does the showHeader method is called multiple times, in the HTML as it is inside *ngFor ? If not how can I call the method mutliple times to provide the value to my *ngIf condition.
Upvotes: 1
Views: 840
Reputation: 1870
what you have written looks fine to me. You could simplify your method this way, but it's the same logic.
showHeader(item){
return (item.group !== 'invalid' && item.group !== 'unkown' && item.group !== 'invisible');
}
Upvotes: 1
Reputation: 2623
Use this approach if you want to have this condition check in multiple components/places by making use of Pipes
@Pipe({
name: 'checkGroup',
})
export class CheckGroupPipe implements PipeTransform {
transform(inputText: any): any {
if(item.group === 'invalid' || item.group === 'unkown' || item.group === 'invisible'){
return false;
}
return true;
}
}
<div *ngFor="let item of groups">
<div class="headerBar" *ngIf="item | checkGroup">
<h3>Hello to the Board</h3>
</div>
</div>
You can check Angular docs to learn more about Pure/Impure pipes
Upvotes: 3
Reputation: 31125
That is normal behavior. If you aren't controlling the change detection strategy, the function will be executed for each change detection cycle. It's always better not to use functions in interpolations and property bindings.
Instead you could evaluate the condition in the controller, assign the output to a variable and use it in the template.
Controller
ngOnInit() {
this.groups.forEach(group => {
if(group.group === 'invalid' || group.group === 'unkown' || group.group === 'invisible'){
group.show = false;
} else {
group.show = true;
}
});
}
Template
<div *ngFor="let item of groups">
<div class="headerBar" *ngIf="item?.show">
<h3>Hello to the Board</h3>
</div>
</div>
I've used ngOnInit
for illustration. You could do check where the groups
variable is actually initialized.
Upvotes: 1