Structural directives in Angular are a special type of directive that changes the structure of the DOM (Document Object Model) to which they are applied. They allow you to control conditional rendering, element repetition and the templates inclusion in the DOM. The three most common structural directives in Angular are "*ngIf", "*ngFor" and "*ngSwitch".
ngIf
The "*ngIf" directive is used for conditional rendering. It adds or removes elements from the DOM based on a Boolean expression.
Example:
// component.ts
import { Component } from '@angular/core';
import { Component } from '@angular/core';
@Component({
selector: 'app-example-ngif',
template: `
<div *ngIf="showElement">
This element will be displayed if showElement is true.
</div>
`
})
export class ExampleNgIfComponent {
showElement = true;
}
ngFor
The "*ngFor" directive is used to render a list of elements based on an iterable expression.Example:
// component.ts
import { Component } from '@angular/core';
import { Component } from '@angular/core';
@Component({
selector: 'app-example-ngfor',
template: `
<ul>
<li *ngFor="let item of listItems">{{ item }}</li>
</ul>
`
})
export class ExampleNgForComponent {
listItems = ['Item 1', 'Item 2', 'Item 3'];
}
ngSwitch
The "*ngSwitch" directive is used to create a conditional selection structure similar to the "switch" in JavaScript.
Example:
// component.ts
import { Component } from '@angular/core';
import { Component } from '@angular/core';
@Component({
selector: 'app-example-ngswitch',
template: `
<div [ngSwitch]="status">
<p *ngSwitchCase="'active'">User is active.</p>
<p *ngSwitchCase="'inactive'">User is inactive.</p>
<p *ngSwitchDefault>User status is unknown.</p>
</div>
`
})
export class ExampleNgSwitchComponent {
status = 'active';
}
These structural directives are powerful for creating dynamic and responsive user interfaces in Angular. They allow manipulation of the DOM structure based on conditions or data provided by the component, providing a declarative way to deal with conditional logic and element repetition.
Nenhum comentário:
Postar um comentário