In case based on one condition we have to display an element/ html section , then ngIf is suitable. But if we have multiple elements / html sections for different value of an expression/ property , then we should use ngSwitch.
Ex:-ngIf
<div *ngIf="showSection()"> show this section if showSection() method returns true </div>
<div *ngIf="showSection()">
show this section if showSection() method returns true
</div>
ngSwitch
<div [ngSwitch]="property.value"> <div *ngSwitchCase="'1'"> show this section if property value is 1 </div> <div *ngSwitchCase="'2'"> show this section if property value is 2 </div> <div *ngSwitchCase="'3'"> show this section if property value is 3 </div> <div *ngSwitchDefault> show this section if property value is neither 1 nor 2 nor 3 </div></div>
<div [ngSwitch]="property.value">
<div *ngSwitchCase="'1'">
show this section if property value is 1
<div *ngSwitchCase="'2'">
show this section if property value is 2
<div *ngSwitchCase="'3'">
show this section if property value is 3
<div *ngSwitchDefault>
show this section if property value is neither 1 nor 2 nor 3
The NgIf directive is used when you want to display or remove an element based on a condition.If the condition is false the element the directive is attached to will be removed from the DOM.The syntax is: *ngIf=""The [ngSwitch] directive on a container specifies an expression to match against. The expressions to match are provided by ngSwitchCase directives on views within the container.Every view that matches is rendered. If there are no matches, a view with the ngSwitchDefault directive is rendered. Elements within the [NgSwitch] statement but outside of any NgSwitchCase or ngSwitchDefault directive are preserved at the location.Example: Three things to keep in mind ngSwitch, ngSwitchCase and ngSwitchDefault.ngSwitch - set the property value of model. For example - viewMode, which is a property in your component.ngSwitchCase - Defines what to render when the value of the property defined in ngSwitchChanges. For ex. when viewMode = 'map'ngSwitchDefault - Defines what to render if the value doesn't match. For ex. when viewMode=undefined. The default will be rendered.Another important point is that we need to set the [ngSwitchCase] within a HTML element otherwise it will not work. Angularwill automatically convert it into a tag. Map View Content... List View Content... 0