Wednesday, November 21, 2018

Angular Custom Directives

Directives in angular are special notations which allows us to extend the behavior of DOM elements in the view template. Like components directives also have a selector and used in the view template to extend the functionality of HTML tags. When the Angular compiler finds a directive in the view template it executes the class behind the directive and modifies the DOM accordingly.

Angular provides built-in directives like ngIf, ngFor etc, apart from these we can also define our own custom directives and use them in the view template.

Custom directives can be created using the ng generate directive command as follows.

ng generate directive

The basic directive class contains a selector and a class to define the directives implementation, we can extend this to provide custom implementation to the directive. The following is the basic class generated when a new directive is created.

import {Directive} from '@angular/core';
@Directive({
  selector: '[mySelector]'
})
export class MyDirective {
  constructor() { }
}

Similar to components which use the @Component decorator, a directive uses the @Directive decorator. In the above code mySelector is the selector of the directive which will be used in the view template and MyDirective is the class which will be used to implement the directive functionality.


Search Flipkart Products:
Flipkart.com

No comments: