2

I am working on requirements where I need to show the list of rows based on some conditions. There is a table cell(td) whose value should be populated based on some condition. I want the following to achieve in angular using *ngIf

if(value1||values2)
{
    if(value3!=null && value4==null)
    {
        //display value 3
    }
    else
    {
     //display value 4
    }
}
else
{
//display default value
}

Pictorial representation of what I want to achieve Diagram I tried this using *ngIf but getting an error **Bidings cannot contain assignments **

<ng-container *ngIf="(value1 || value2); else showDefault">
    <ng-container *ngIf="value3!=null && value4==null; else showValue4">
    </ng-container>
    <ng-template #showValue4>
    </ng-template>
</ng-container>
<ng-template #showDefault>
</ng-template>

Is there any other way to achieve this?

Virender Thakur
  • 327
  • 3
  • 12

2 Answers2

4

Although your solution seems fine, another way would be to use the ngTemplateOutlet directive.

That way you can have your ngTemplates ready and decide what you're going to use by the name of the template like this:

<ng-container *ngTemplateOutlet="selected">
  This text is not displayed
</ng-container>

<ng-template #template1>
  <p>This is our template.</p>
</ng-template>

<ng-template #template2>
  <p>This is another template.</p>
</ng-template>

<ng-template #template3>
  <p>This is one more template.</p>
</ng-template>

<button (click)="selected = template1" >1</button>
<button (click)="selected = template2" >2</button>
<button (click)="selected = template3" >3</button>

Here you can read more.

Here I created a StackBlitz, to play around.

Richard Jessop
  • 897
  • 1
  • 12
  • 19
StPaulis
  • 2,844
  • 1
  • 14
  • 24
  • Thank you for the example. But I want to achieve the If else example that I give in the questions. In your example, I can relate only 2 conditions. Can you provide the same for multi conditions. – Virender Thakur Jul 16 '21 at 16:57
  • Of course you can! Look at the StackBlitz again: https://stackblitz.com/edit/angular-ivy-zekhbs?file=src/app/app.component.ts – StPaulis Jul 16 '21 at 17:32
  • `NgTemplateOutlet` is a very special feature that Angular provides, I would recommend you to read the articles I shared with you and I am sure that it will help you a lot in the future. – StPaulis Jul 16 '21 at 17:42
  • I have just added the diagram of what I want to achieve using nested conditinos. Is there any way to do this as shown in the diagram. – Virender Thakur Jul 16 '21 at 18:30
  • If you understand how outlet template works, you can do it on your own. All the information is here... – StPaulis Jul 16 '21 at 19:45
0

try

<ng-container *ngIf="value3 && !value4; else showValue4">