Kiran Mohanty
What is the difference between ngIf and ngSwitch ?

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

  1. <div *ngIf="showSection()">
  2. show this section if showSection() method returns true
  3. </div>

ngSwitch

  1. <div [ngSwitch]="property.value">
  2. <div *ngSwitchCase="'1'">
  3. show this section if property value is 1
  4. </div>
  5. <div *ngSwitchCase="'2'">
  6. show this section if property value is 2
  7. </div>
  8. <div *ngSwitchCase="'3'">
  9. show this section if property value is 3
  10. </div>
  11. <div *ngSwitchDefault>
  12. show this section if property value is neither 1 nor 2 nor 3
  13. </div>
  14. </div>
By Kiran Mohanty in Angular on Sep 23 2020
  • Pranam Bhat
    May, 2021 21

    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.

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS