0

Could you please guide me how to use *ngIf in Angular 9 for multiple conditions as shown below. The following is not working for me.

*ngIf="abc !! xyz"

However, it is working for an individual condition like

*ngIf="abc" 

or

*ngIf="xyz"

and the TS code is:

radioButtonChanged($event){
   let radioValue = event.target['value'];

   console.log(radioValue);
   if(radioValue =='abc'){
     this.abc = true;
     this.xyz = false;
   } else{
     this.abc=false;
     this.xyz = true;
   }      
}
HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
hali
  • 5
  • 1
  • 8
  • 1
    `*ngIf="abc || xyz"` – Roy Jan 08 '21 at 08:22
  • use a function for a more complex condition. – HDJEMAI Jan 08 '21 at 08:27
  • 1
    @HDJEMAI: Binding a function to a directive will trigger it for each change detection cycle in case of default CD strategy. It isn't recommended. – ruth Jan 08 '21 at 08:31
  • Some times when changes are not detected, it cannot be helpful ? – HDJEMAI Jan 08 '21 at 08:33
  • Does this answer your question? [angular 4: \*ngIf with multiple conditions](https://stackoverflow.com/questions/43801823/angular-4-ngif-with-multiple-conditions) – Roy Jan 08 '21 at 08:34
  • Let me add my ts code for more clarity – hali Jan 08 '21 at 08:35
  • @HDJEMAI; That didnt work – hali Jan 08 '21 at 08:47
  • I am trying to achieve to show 3 html elements based on radio button selection. Based on radio button selection I can able to display elements without any issues. However, I want to display a common html element based on any selection. – hali Jan 08 '21 at 08:54
  • some times you may need to trigger change detection manually, you may also make form touched, in some specific cases it helps, consider providing a `stackblitz` demo to show your issue. – HDJEMAI Jan 08 '21 at 09:04
  • It is resolved now. I took one more variable for defining common fields. 3 variables for ex ; abc, xyz, pqr – hali Jan 08 '21 at 15:48

2 Answers2

0

You can use if-else concept here:

<div *ngIf="condition1; else condition2"></div>

<ng-template #condition2>
  <div> whatever </div>
</ng-template>

The way you are using it; the || operator will work as a binary operator like && .That is not the correct way of doing it.

METHOD 2:

You can check all the conditions you want in the component.ts file and then assign the result of your conditions to a variable and bind it with *ngIf.

This will be kind of tedious but the HTML will remain clean.

Srikar Phani Kumar M
  • 1,069
  • 1
  • 3
  • 8
0

You can do this

// If you want both the conditions to be true 
<div *ngIf="abc && xyz"> whatever </div>

// If you want either of them to be true
<div *ngIf="abc || xyz"> whatever </div>

// If you want neither of them to be true
<div *ngIf="!abc && !xyz"> whatever </div>
Srikar Phani Kumar M
  • 1,069
  • 1
  • 3
  • 8