Angular

Directives

Angular directives are used to modify appearance and attach additional behaviour to DOM elements.
There are three types of directives:

  • Components – directives that contain template (not discussed in this post)
  • Attribute directives – used to change behaviour as well as appearance of DOM element. The name of the directives must be inside square brackets. The most frequently used attribute directives include ngStyle and ngClass.
    a) ngStyle – allows to change the style attribute of component or element:

    <span [ngStyle]="{'color': 'red'}">{{sister.name}}</span>
    

    b) ngClass – modifies the class attribute of component or element:

    <span [ngClass]="['my-class']">{{sister.name}}</span>
    

    It is possible to combine attribute directives with condition. For ngStyle we could write:

    <span [ngStyle]="condition && {'color': 'red'}">
    {{sister.name}}
    </span> 
    // font is red when "condition" is set to true
    

    And for ngClass directive:

    <span [ngClass]="(name=='Adam')
    ?'first-class'
    :'second-class'">
    {{sister.name}}
    </span> 
    // "first-class" is used when "name" 
    // is equal to "Adam". 
    // Otherwise, "second-class" is attached to the element
    
  • Structural directives – allow to add, remove and manipulate elements in the DOM. The name of the directives is always preceded by an asterisk (*). The most popular built-in structural directives are ngIf and ngFor. The usage of them could be as follows:
    a) ngIf – hides or shows HTML element depending on the value of booelan expression:

    <span *ngIf="sister">{{sister.name}}</span>
    

    b) ngFor – allows to loop through the list of elements

    <ul>
      <li *ngFor="let sister of sisters">{{sister.name}}</li>
    </ul>
    

    Here it’s necessary to mention about ngSwitch directive.
    In simplified term, the principle of its operation is as follows: value, that is assigned to the ngSwitch establishes which case is chosen (visible):

    <div [ngSwitch]="person.gender">
      <span *ngSwitchCase="'male'">male</span>
      <span *ngSwitchCase="'female'">female</span>
      <span *ngSwitchDefault>-</span>
    </div>
    

    It seems that we should write *ngSwitch instead of [ngSwitch], because we are dealing with structural directive. However, ngSwitch it’s an attribute directive that controls structural directives (ngSwitchCase and ngSwitchDefault). Because of that we should always write [ngSwitch].

Leave a Reply

Your email address will not be published. Required fields are marked *