Search code examples
angular5ngforangular-ng-if

*ngFor and *ngIf on a <tr> element in Angular 5


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!


Solution

  • 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; } );
        }
    }