Directives in Angular 2
Posted By : Anchal Gaur | 26-Feb-2018
Directives are one of the important key features in Angular applications. Directives are something that initiates new syntax or markup. They are indications of the DOM elements which provides some special behavior to DOM elements and tells the compiler of HTML to attach.
There are three types of directives in the Angular2 application.
1. Components
It is a directive in the angular2 application which includes the view or design layout of application and also contains the business logic. It is very essential to divide the application into chunks.In another context, we can say that component is a directive which is always associated with template directly.
2. Structural directives:
It is another kind of directive and it has the ability to change the behavior of DOM by adding and removing elements. NgIf, NgFor, NgSwitch are the best example of this kind of directive.
3. Attribute directives:
It has also the same ability which is in structural directive i.e. it also changes the behavior of DOM by adding and removing DOM elements. For example, NgStyle is an attribute which changes the style of elements at the same time.
Directive LifeSpan
Angular manage lifespan of the directive by itself same as in case of components. Angular is used to render and create the directive. When the related modal changes, it updates the data and angular destroys the corresponding directive before removing from the DOM.
There are some lifecycle sequences for the directive.
(i) ngOnChanges: It happens where Angular sets the data-bound property. from here we can get the present or current and previous value of the changed object.
The syntax of Directive
ng generate directive highlight
Directives must be declared in angular modules in the same way as the components generate.
Code
src/app/highlight.directive.ts
import { Directive } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor() { }
}
The directive symbol which is shown in the code provides the angular @Directive decorator.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Anchal Gaur
Anchal has a good knowledge of HTML,CSS and Javascript. She is working here as a UI Developer. Her hobbies are travelling and to read novels in free time.