Reputation: 10294
In my Angular 5 app I'm looping to create tr
elements:
<tr *ngFor="let element of elements">
but I only want to show the row if certain conditions are met. I know I can't use *ngFor
and *ngIf
together, but I'm not seeing how to get around this.
I saw a post saying to add a template inside the tr with an [ngIf]
construct but that doesn't seem to be valid syntax any longer. If I try it like so:
<tr *ngFor="let element of elements">
<template [ngIf]="element.checked || showUnchecked">
then I get runtime errors.
AppComponent.html:14 ERROR Error: StaticInjectorError(AppModule)[NgIf -> TemplateRef]:
StaticInjectorError(Platform: core)[NgIf -> TemplateRef]:
NullInjectorError: No provider for TemplateRef!
Upvotes: 2
Views: 8683
Reputation: 21
ng-container would work instead of template
<table><tr *ngFor="let element of elements">
<ng-container *ngIf="element.checked || showUnchecked">
<td></td>
<td></td>
</ng-container>
</tr>
<table>
Upvotes: 1
Reputation: 427
Create a getter that return the property elements already filtered. Something like
get filteredElements() {
if( this.showUnchecked ) {
return this.elements;
} else {
return this.elements.filter( () => { return this.checked; } );
}
}
Upvotes: 1