Friday, April 14, 2017

Directives exist in Angular 2, but they are not what you are used to in Angular 1.

Components are, in fact, a kind of Angular 2 directive so if you are using Angular 2 at all you are probably already using directives. Structural directives and attribute directives are the other kinds of directives. Beyond ngIf and ngFor some of the similar tag-based things that may be done in Angular 2 markup are structural directives. ngSwitch is the best example and I suppose you may make your own stuff of this ilk.

<ng-container [ngSwitch]="model.inTheMoodFor">
   <ng-container *ngSwitchCase="foodEnum.ghetto">
      Burger King
   </ng-container>
   <ng-container *ngSwitchCase="foodEnum.greek">
      <a href="http://www.athenianbargrill.com/">Athenian</a>
   </ng-container>
   <ng-container *ngSwitchDefault>
      Olive Garden
   </ng-container>
</ng-container>

 
 

Attribute directives like <p myHighlight>Highlight me!</p> sit a tag and warp how it behaves. https://angular.io/docs/ts/latest/guide/attribute-directives.html has the following example for myHighlight directive to make this tag decoration work out:

import { Directive, ElementRef, Input } from '@angular/core';
@Directive({ selector: '[myHighlight]' })
export class HighlightDirective {
   constructor(el: ElementRef) {
      el.nativeElement.style.backgroundColor = 'yellow';
   }
}

No comments:

Post a Comment