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
import {Directive, Input,ElementRef} from 'angular2/core';
import {CORE_DIRECTIVES} from 'angular2/common';
import {TemplateRef, ViewContainerRef} from 'angular2/core';

/*Angular 2 myAngular2AttributeDirective*/

        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() {

    private _changeBackGroundAndZoom(color:string,textColor:string,fontSize:string) { = color; = textColor; = fontSize;

angular 2 attribute directive