Search code examples
angularangular-ng-if

Angular wildcard string comparison in html


This might be a very basic question and I know various ways to accomplish what I want. But, I would like to know if it is possible to use wildcards in *ngIf comparisons.

Imagine following code:

<ng-container *ngIf="test == 'teststring'">

</ng-container>

I would like to know if it is possible to for example use:

<ng-container *ngIf="test == '*teststring'">

</ng-container>

So that it could be 0teststring or 1teststring.

Thank you in advance!


Solution

  • What you're looking for is test.endsWith('teststring'). However, calling functions in the template is bad, because they are called on every tick. Use a pure pipe instead:

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({ name: 'endsWith', pure: true })
    export class EndsWithPipe implements PipeTransform {
      public transform(a_sString: string, a_sEndsWith: string): boolean {
        return a_sString.endsWith(a_sEndsWith);
      }
    }
    

    Usage:

    *ngIf="test | endsWith:'teststring'"