Spread the love

Directives are custom tags and custom attributes of html which is controlled by class and decorators. Using directives we can change the behaviour, style and logic of a specific area.

Example:

helloworld.component.ts

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: ‘hello-world’,
  template: ‘Hello world component/directive’
 
})
export class HelloWorld implements OnInit {

 constructor() {

   
  }
  ngOnInit() {

  }
}

Xyz.compenent.html

<hello-world></hello-world>

Output:
Hello world component/directive

Types of Directives:

  1. Component 
  2. Attributes Directive
  3. Structural Directive

1. Component :

Angular page is group of components, we use component everywhere in the angular project. so, we can say that components are main part of an angular application.
Component contains decorators and class. Decorator contains the details of html template, css, change detection strategy and the component selector name.

Let’s create a component using ng generate command

ng g component helloworld

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: ‘hello-world’,
  template: ‘Hello world component/directive’
 
})
export class HelloWorld implements OnInit {

 constructor() {

   
  }
  ngOnInit() {

  }
}

2. Attribute Directive

Attribute directive is used the change the behaviour of element, component or directive. there is some in-build structural directive ngStyle, ngClass, ngModel.

Example:

<div [ngClass]="isActive ? 'active' : ''">This div is active container</div>

3. Structural Directive

Structural directives are directives which add or remove the elements from the dom.

There is 3 in-built structural directives in angular.

  1. ngFor
  2. ngIf
  3. ngSwitch

Example:

<hello-world *ngIf="isActive" [post]="post"></hello-world>

Leave a Reply