Search code examples
angularpipeconditional-statementsangular7angular-material-7

Is it possible to apply a conditional pipe which itself contains a condition?


I have a dropdown (input + autocomplete) where I can type a string or select an object from the dropdown list. I want to use the pipe only when the value in the input is of type string. If user selects a value from dropdown, I need to remove the custom pipe.

I want to apply the custom pipe the typeof option.name is String. and to remove it if type is Object.

Tried the link, but in vain Angular 2 Pipe under condition

Actual code:

<mat-option *ngFor="let option of sortedOptions"
       [innerHTML]="option?.name | highlight : userControl.value" >

What I am not able to understand is how to check String type here:

{{ typeof(option.name) ? (option?.name | highlight : userControl.value)  : option.name }}

Solution

  • You can create helper method on your component like this:

    isString(val) { return typeof val === 'string'; }
    

    Now you can check your condition like this:

    {{ isString(option.name) ? (option?.name | highlight : userControl.value)  : option.name }}
    

    Here is the working demo for you