Home > Back-end >  What is the difference b/w add class condition by the help of *ngIf and [ngClass]?
What is the difference b/w add class condition by the help of *ngIf and [ngClass]?

Time:06-29

What is the difference between code 1 and code 2

1

<mat-sidenav *ngIf="menuClicked"  mode="side" fixedTopGap="56" opened="true">
    <report-sidebar [isIconShow]="menuClicked"></report-sidebar>
</mat-sidenav>
<mat-sidenav *ngIf="!menuClicked"  mode="side" fixedTopGap="56" opened="true">
    <report-sidebar [isIconShow]="menuClicked"></report-sidebar>
</mat-sidenav>

and

2

<mat-sidenav  [ngClass]="menuClicked?'col-3':'col-1'" mode="side" fixedTopGap="56" opened="true">
    <report-sidebar [isIconShow]="menuClicked"></report-sidebar>
</mat-sidenav>```

CodePudding user response:

I've not used that method personally but you can use this in your use case

<mat-sidenav
    
    [class.col-3]="menuClicked"
    [class.col-1]="!menuClicked"
    ...>
    <report-sidebar [isIconShow]="menuClicked"></report-sidebar>
</mat-sidenav>

CodePudding user response:

For code1 *ngIf="menuClicked",

Let me assign menuClicked = true; If menuClicked value is false, the whole mat-sidenav don't display. I mean the following code not displayed in html.

<mat-sidenav *ngIf="menuClicked"  mode="side" fixedTopGap="56" opened="true">
    <report-sidebar [isIconShow]="menuClicked"></report-sidebar>
</mat-sidenav>

And the following code worked.

<mat-sidenav *ngIf="!menuClicked"  mode="side" fixedTopGap="56" opened="true">
    <report-sidebar [isIconShow]="menuClicked"></report-sidebar>
</mat-sidenav>

For code2 [ngClass]="menuClicked?'col-3':'col-1'",

It change class value only depends on menuClicked value. I mean if menuClicked value is true, class has col-3 property.

<mat-sidenav  mode="side" fixedTopGap="56" opened="true">
    <report-sidebar [isIconShow]="menuClicked"></report-sidebar>
</mat-sidenav>

If menuClicked value is false, class has col-1 property.

<mat-sidenav  mode="side" fixedTopGap="56" opened="true">
    <report-sidebar [isIconShow]="menuClicked"></report-sidebar>
</mat-sidenav>

The main difference of your code for *ngIf and [ngClass] is that *ngIf work for the whole html tag to display or not and [ngClass] only change class property base on condition.

  • Related