Home > Enterprise >  Angular: Check values before pipe for correct type
Angular: Check values before pipe for correct type

Time:02-04

I have a value called _myValue: string | undefined. I get it from the TS via getter:

get myValue(): string | undefined {
    return this._myValue;
}

In the template I want to send it through a pipe.

<td>
  {{ myValue| prinValues }}
</td>

The problem:

This pipe prinValues only accepts string | number (no undefined).

This of course leads to compilation problems. How can/should I ensure this? The pipe itself comes from an external library, so I won't be able to modify it.

CodePudding user response:

The simplest way is to not render the element (or render a placeholder) when myValue is null or undefined:

<td>
  <ng-container *ngIf="myValue">
    {{ myValue| prinValues }}          
  </ng-container>
  <ng-container *ngIf="!myValue">
    no value        
  </ng-container>
</td>

CodePudding user response:

In case the pipe is able to transform an empty string to a proper value, you can use nullish coalescing to set the value to empty string if it's undefined:

get myValue(): string {
    return this._myValue ?? '';
}

Otherwise, you can use the approach from @Zerotwelve's answer.

CodePudding user response:

Another inelegant solution is to disable the AoT template type-checking altogether using the $any() function.

<td>
  {{ myValue| $any(prinValues) }}
</td>

But as the documentation says, it only silences the type checking errors, and so renders the AoT template type-checking for that variable useless.

  •  Tags:  
  • Related