Angular
Built-in Directives
Use *ngIf, *ngFor, ngClass, and ngStyle to shape the DOM.
By EZ4Code Team
directivesngIfngFor
Code
import { Component } from "@angular/core";
import { NgIf, NgFor, NgClass, NgStyle } from "@angular/common";
@Component({
selector: "app-directives",
standalone: true,
imports: [NgIf, NgFor, NgClass, NgStyle],
template: `
<p *ngIf="show; else loading">Visible</p>
<ng-template #loading>Loading...</ng-template>
<li *ngFor="let item of items; let i = index">
{{ i + 1 }}: {{ item }}
</li>
<div [ngClass]="{ active: isActive, disabled: !isActive }">Class</div>
<div [ngStyle]="{ color: isActive ? 'green' : 'red' }">Style</div>
`
})
export class DirectivesComponent {
show = true;
items = ["a", "b", "c"];
isActive = true;
}Explanation
Structural directives reshape the DOM: *ngIf conditionally renders and *ngFor loops over collections. Attribute directives alter element appearance via [ngClass] and [ngStyle]. The asterisk is syntactic sugar that unwraps into ng-template elements.
More Angular Snippets
Component Basics
Define an Angular component with selector, template, and styles.
Template Syntax & Binding
Interpolation, property, event, and two-way binding in Angular templates.
Pipes & Custom Pipe
Transform template values with built-in and custom pipes.
Services & Dependency Injection
Create an injectable service and consume it in a component.
Routing Configuration
Define routes with params, lazy loading, and redirects.
Reactive Forms
Build a typed reactive form with FormBuilder and validators.