Angular 4 Directives – Lesson 3.3

3.2 Attribute Directives

Here directive is just a class with decorator @Directive and this allows us to specify the directive’s selector.

  • Using custom attribute directive we can change the color, back-ground, font-size etc., of the HTML host element by using ElementRef
  • Renderer class is a built-in service that provides an abstraction for UI rendering manipulations.

Let’s create a custom attribute directive “ShowAlert

Step 1: Create a folder and name it as CustomDirective: /src/app/CustomDirective

Step 2: Now create a typescript file to create your own attribute directive under the associated folder created. And then import Directive, ElementRef, HostListener, Renderer from @angular/core library.

Step 3: And provide your selector name, here I’ve named it as ShowAlert, and create a class that make this directive visible to the component i.e.,add export before the class.

File: app.myDirective.ts

Step 4: Now define contructor for FirstAttrDirective class, and define the style and events using renderer.

For setting up styles,

Renderer.setElementStyle(rendererElement:any, styleName: string, styleValue: string)

(or)

ElementRef.nativeElement.style

For creating events,

Renderer.listen(parentElement: any, name: string, callBack: function)

Step 5: Create your component

File: app.component.ts

Step 6: Add component and Directive in the declaration[ ] of the NgModule  i.e., AppModule

Step 7:  Create a main.ts to bootstrap the NgModule

Step 8: Create a HTML file in /src/

File: CustomDirective.html

Refer required scripts shim.min.js, zone.js, system.src.js, system.config.js and refer the main.js from CustomDirective folder

Output: Default color will be blue, on mouseover font size get increased and changes its color to red, on mouseout will change color to blue and decrease its font size.

Tadaaaa.. 🙂

One thought to “Angular 4 Directives – Lesson 3.3”

Leave a Reply

Your email address will not be published. Required fields are marked *