Directives
Directives in Angular are instructions in the DOM that tell Angular how to manipulate the behavior and appearance of elements. There are two types of directives: structural directives and attribute directives.
Syntax:
<div *ngIf="condition">Content to show when condition is true</div>
Angular provides two types of directives:
- Structural Directives: These directives alter the DOM layout by adding, removing, or manipulating elements based on certain conditions. Examples include *ngIf, *ngFor, and *ngSwitch.
- Attribute Directives: These directives modify the appearance or behavior of a DOM element. They are applied to elements as attributes. Examples include ngStyle, ngClass, and ngModel.
Features of Directives:
- Directives modify the DOM based on certain conditions or criteria.
- They can add, remove, or manipulate elements in the DOM.
- Directives can be applied conditionally using structural directives like *ngIf and *ngFor.
- Attribute directives modify the appearance or behavior of elements based on data or conditions.
- Directives promote reusability and maintainability by encapsulating specific behavior.
Code Example:
To generate a new directive, we can use the following command.
ng generate directive upperCase
<!-- app.component.html -->
<form>
<div>
<label>Name: </label>
<input
appUpperCase
type="text"
name="name"
minlength="4"
[(ngModel)]="name"
#nameInput="ngModel"
required
[ngClass]="{ 'is-invalid': nameInput.touched && nameInput.invalid }"
/>
<div *ngIf="nameInput.touched && nameInput.invalid">
Minimum length of name is 4 characters
</div>
</div>
<div>
<label>Age: </label>
<input
type="number"
name="age"
[(ngModel)]="age"
#ageInput="ngModel"
required
[ngStyle]="{
'border-color': ageInput.invalid && ageInput.touched ? 'red' : ''
}"
/>
<div *ngIf="ageInput.touched && ageInput.invalid">Age is required</div>
</div>
</form>
//app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
name: string = '';
age!: number;
}
//upper-case.directive.ts
import { Directive, HostListener, ElementRef } from '@angular/core';
@Directive({
selector: '[appUpperCase]',
})
export class UpperCaseDirective {
constructor(private el: ElementRef) { }
@HostListener('input')
onInput(event: any) {
const input = this.el.nativeElement.value.toUpperCase();
this.el.nativeElement.value = input;
}
}
Output:
Difference between directives and components
In Angular, directives, and components are essential concepts that help to build dynamic and interactive web applications. While they both play significant roles, understanding their differences and use cases is crucial for effective Angular development.