Angular 2 Attribute Directive

Angular 2 Attribute Directive alters the Element by changing the behavior and/or the appearance of this element.

(e.g. NgClass : it adds a class to an element. e.g. span)

We have three kinds of directives: Components, Structural and Attribute.

angular 2 attribute
angular 2 attribute

We want to create an attribute zoom in (on Mouse Enter zoom in)

live example and resources at the end of the article

Angular 2 Attribute directives
Angular 2 Attribute directives

<p [zoomIn]=”blue”> Use Angular 2 Attribute Directive please : ) </p>

  1. Import the @Directive decorator. (import {Directive} from ‘angular2/core’;)
  2. To identify the attribute directive we set a CSS selector. (@Directive({ selector: ‘[zoomIn]’ }))
  3. Do not use ng as prefix for your attribute directive.
  4. We add a public input to our attribute Directive to set the background color when zoom in. @Input(‘zoomIn’) eLBackgroundColor: string;
  5. The attribute directive changes the element background if mouse enter and zoom out when mouse leave.
  6. We configure the mouse event in the host
  7. The host property refers to the DOM element where the attribute is called. (in our case <p>)

 

The code source of our attribute directive :

/**
 * Created by Tareq Boulakjar. from angulartypescript.com
 */
import {Directive, Input,ElementRef} from 'angular2/core';
import {CORE_DIRECTIVES} from 'angular2/common';
import {TemplateRef, ViewContainerRef} from 'angular2/core';

/*Angular 2 myAngular2AttributeDirective*/

@Directive(
    {
        selector: '[zoomIn]',
        host: {
            '(mouseenter)': 'onMouseEnter()',
            '(mouseleave)': 'onMouseLeave()'
        }
    }
)

export class Angular2AttributeDirective {
    @Input('zoomIn') eLBackgroundColor: string;

    private _defaultColor = 'green';

    constructor(private el: ElementRef) { }

    onMouseEnter() {
        this._changeBackGroundAndZoom(this.eLBackgroundColor || this._defaultColor ,"white","18px");
    }

    onMouseLeave() {
        this._changeBackGroundAndZoom(null,"black","12px");
    }

    private _changeBackGroundAndZoom(color:string,textColor:string,fontSize:string) {
        this.el.nativeElement.style.backgroundColor = color;
        this.el.nativeElement.style.color = textColor;
        this.el.nativeElement.style.fontSize = fontSize;
    }
}

angular 2 attribute directive