ngSwitch Directive in Angular 8
Angular 8 ng-Switch Directive
The ng-Switch Directive hides and shows the HTML elements depending on an expression.
Child elements with the ng-switch-when directive will be displayed if it gets a match; otherwise, the component and its children will be removed.
We could also define a default section, by using the ng-switch default directive, to show a section if no any other part gets a match.
Syntax:
ng-SwitchCase
In Angular ngSwitchCase directive, the inner elements are placed inside the container element. It is applied to the inner elements with a match expression. When the value of the match expression matches the value of switch expression, the correlated inner element is added in the DOM. All other inner elements are removed from the DOM.
If there is more than one match, then all the matching elements are added to the DOM.
ng-SwitchDefault
We can apply the ng-switchDefault directive in Angular 8. The element with ngSwitchDefault is displayed if no match found. The inner element with ngSwitchDefault can be placed anywhere inside the container element and not necessarily at the bottom line. If we add more than ngSwitchDefault directive, and all of them are displayed.
Any elements placed inside the container element, but outside the ngSwitchCase or ngSwitchDefault elements are displayed the same as it is.
ngSwitch Directive Example
Write the given code in app.component.ts file of the application:
class item { name: string; val: number; } export class AppComponent { Items: item[ ]=[{name: ’one’,val: 1}, { name: ’two’,val: 2},{name: ‘three’, val: 3}]; selectedValue: string=’one’; }
Use the below code in the app.component.html file of the application.
One is pressedTwo is pressed;Default Option