8. Angular Directive - Theory. Tutorial - 8

In Angular, directives are a way to extend and manipulate the Document Object Model (DOM) in your web applications. They are used to create reusable components, add behavior to elements, and modify the structure or appearance of the DOM. There are three main types of directives in Angular:


 1. Component Directive: Components are the most common type of directive in Angular. They are used to create reusable, self-contained user interface components. Components include their own templates, styles, and behaviors.

@Component({

  selector: 'app-component-login',

  templateUrl: './login.component.html',

  styleUrls: ['./login.component.css']

})


2. Attribute Directives: Attribute directives are used to change the appearance or behavior of an element. They are implemented as attributes of HTML elements.

    <p [ngStyle]="{'background': isRed ? 'red' : 'green'}"> Attribute Directive</p>

 

3. Structural Directives: Structure directives change the structure of the DOM by adding or removing elements. They are prefixed with an asterisk (*) in HTML.

  •     The 3 most popular structured directives are -
    1. ngIf
    2. ngFor
    3. ngSwitch

  • ngIfIt is used to create or remove a part of the DOM tree depending on a condition. 
        Example - 
            <div *ngIf=”movie”>{{movie.name}}</div>
            <div template=”ngIf movie”>{{movie.name}}</div>

            <ng-template [ngIf]=”movie”><div>{{movie.name}}</div></ng-template>

         








  • ngFor It is used to customize data display. It is mainly used to display a list of items using an iterative loop.
           Example - 
                        <div *ngFor="let movie of movies">{{movie.name}}</div>
                        <div template="ngFor let movie of movies">{{movie.name}}</div>

                        <ng-template ngFor let-movie [ngFor]="movies">{{movie.name}}</ng-template>


 

     Get and use the index number of *ngFor loop -

    


  • ngSwitch : It's like JavaScript switches. It can display one of several possible components based on a switch state. Angular only places the selected element in the DOM.
            Example - 
            <div> 
            <ng-template [ngSwitch]="'sad'">
            <horror-movie [movie]="movie"></horror-movie>
            </ng-template> 
            </div>


Post a Comment

0 Comments