Search code examples
angularif-statementcomponentsasync-pipe

How to use the @if angular with async pipe and alias for else block?


I have the follow case, when @if validatior (introduced in angular 17) is used with else block, is validated with an observable and using an alias in order to avoid multiple subscriptions, What is the best approach to use alias with observable in if else block?

Is possible to resolve with other if block nesting the if and else validation. What would be the best implementation to avoid extra block?

   @if (validation$ | async; as validation) {
      @if (validation === 'if') {
        <h2>If block</h2>
        <div>Message: {{validation}}</div>
      } @else {
        <h3>Else block</h3>
        <legend>{{validation$ | async}}</legend>
      }
    }

Expecting a resolution like this (pseudocode), this way is not supported:

 @if ((validation$ | async; as validation) === 'if') {
     <div>Message: {{validation}}</div>
 } @else {
     <legend>Other component: {{validation}}</legend>
 }

Should I use the extra if block?

Stackblitz sample


Solution

  • This is one of the uses cases that will be covered by the new @let template variable declaration that will land in 18.1

    @let validation = validation$ | async;
    
    @if(validation === 'if') {
         <div>Message: {{validation}}</div>
    } @else {
         <legend>Other component: {{validation}}</legend>
    }
    

    Btw don't forget that the AsyncPipe returns null until the first value has been sent over the pipe.