Wednesday, 16 June 2021

 Structural Directives in Angular


Structural directives are responsible for HTML layout. They shape or reshape the DOM's structure, typically by adding, removing, or manipulating elements.

There are three built-in structural directives, NgIfNgFor and NgSwitch.

NgFor:
 It is a repeater directive that customizes data display. It can be used to display a list of items.

NgIf:
 It removes or recreates a part of DOM tree depending on an expression evaluation.


Example:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  //title = 'StructuralDirective';

  title = "Welcome to Structural Directive Tutorials";

  showElement = true;

  color = "green";

  colors = ['red','green','orange'];

}

<h2>{{title}}</h2>

<!-- This will show only if showElement property is True in component class-->
<p *ngIf="showElement">This is ngIf directive</p>

<!--ngSwitch-->
<div [ngSwitch]="color">
  <div *ngSwitchCase="'red'">This is red</div>
  <div *ngSwitchCase="'green'">This is Green</div>
  <div *ngSwitchDefault>Invalid color</div>
</div>

<!--ngFor-->
<ul>
  <li *ngFor="let color of colors">{{color}}</li>
</ul>



Open the terminal window and enter the below command:



You will see the following on your Browser:












No comments:

Post a Comment