Angular 2 Directive

Angular 2 Directive

Angular 2 Directive used to change the appearance or behavior of any DOM element.

There are three types of Angular directives.

  1. Component – Component directive with a template attribute.
  2. Attribute directives.
  3. Structural directives – Directives that will extend the power of HTML.

Attribute Directive

Directives that will change the behavior of a component or html like ngClass and ngStyle.


ngStyle is type attribute directive and it is used to write inline css on html tag or on Angular selector. It is equivalent to element’s style attribute.

  selector: 'directive-example',
  template: `
    <p [ngStyle]="{
        'font-size': '12px',
        'font-weight': 'bold'
export class DirectiveComponent {

Note – Directive name must be enclosed in square brackets.


ngClass directive is used to apply css class over HTML tags.

  selector: 'directive-example',
  template: `
    <p[ngClass]="['center-text']">Vikash Kumar</p> `,
  styles: [` .center-text { text-align: center; } `] 

 export class DirectiveComponent { }


Full-stack web and mobile app development company Contact Us : Skype: indore.webcoder Email: Sales: +91 8085506229