Directives provide a variety of ways to abstract the HTML UI elements, attributes, classes, expressions and styles. There are tons of use cases in Angular for Directives which are described as follows:

  • Directives for styles
import {Directive, HostBinding, HostListener} from '@angular/core'

@Directive({
    selector: '[autoGrow]'
})

export class AutoGrowDirective {
    @HostBinding('style.width.px')
    width:number = 120;

    @HostListener('focus')
    onFocus() {
        this.width = 500;
    }

    @HostListener('blur')
    onBlur() {
        this.width = 120
    }
}
  • Built-in Directives

There are many built-in directives in Angular. The frequently used ones are *ngIf and *ngFor.

The *ngIf is used for conditional expressions.

@Component({
    selector: 'user',
    template: `
        <ul>
            <li *ngIf = 'show'>show or hide</li>
        </ul>
    `
})

The *ngFor is used for loops.

@Component({
    selector: 'user',
    template: `
        <ul>
            <li *ngFor = 'let stu of students'></li>
        </ul>
    `
})