Sunday, October 28, 2018

Understanding Angular Directives


Directives in angular can be used to implement life-cycle hooks. Directives are declared with @Directive attribute. In Angular there are 3 types of directives,
  1. Component 
  2. Structural
  3. Attribute
Component directives is a directive which comes with a template. Angular components are subset of directives. A component must belong to a NgModule in order for it to available to another component. 


Structural directives (link)
Used to deal with manipulating DOM elements. Examples of structural directives are *ngIf, *ngSwitch and *ngFor

NgIf directive
ngIf doesn't hide elements with CSS. It adds or removes them physically. Internally angular translates the *ngIf attribute to a <ng-template> element, wrapped around the host element. (What is a ng-template)

You can also create custom structural directives.

Attribute directives (link)
Changes the appearance or behavior of a DOM element.  You create a class, decorate it with @Directive decorator. After that you can pass in the ElementRef in constructor and change the behavior of the element.

You can make this more dynamic by adding HostListener and listening to DOM events.

Even more you can pass input parameters to the attribute directives. 

Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook