Creating A Directive in Angular 4

Posted By : Pawanpreet Singh | 28-Dec-2017

Objective:

  • Learn the basics of @Directive decorator
  • Learn how to use your directive with elements using attribute.

Learning Decorator:

We will use ppNoZero name for our directive and will attach it to code like shown below:
 
                <input type=”number” ppNoZero />

        
The team at Angular recommends that we should use some prefix in our directive, here we have used 'pp' as a prefix.
 
Code:
                import {
   Directive, HostListener, Input
 } from '@angular/core';
 import {
   DefaultValueAccessor, NG_VALUE_ACCESSOR
 } from '@angular/forms';
  @Directive( {
   selector : 'input[ppNoZero], textarea[ppNoZero]',
   providers: [
     { provide: NG_VALUE_ACCESSOR, useExisting: NoZeroDirective, multi: true }
   ],
  } )
 export class NoZeroDirective extends DefaultValueAccessor {
    // set a new value to the field and model.
   private set value( val: any ) {
      // update element
     this.writeValue( val );
      // update model
     this.onChange( val );
    }
 
    /**
    * Updates the value on the input event.
    */
   @HostListener( 'input', ['$event.type', '$event.target.value'] )
   onInput( event: string, value: string ): void {
     this.updateValue( event, value );
   }
    /**
    * restrict zero on an input value.
    *
    * @param {string} value - input value
    * @param {string} event - input event
    */
   private updateValue( event: string, value: string ): void {
      //restricts zero on an input value
     this.value =  value.replace(/^0/g, '');;
    }
  }

        
 
We have created a directive using @Directive annotation decorator in our angular class.
Here we said it will be used on two selectors input and text area which has our directive in it.
 
Our directive will work only on input events if user inputs zero in initial place it will restrict it and replace it with the empty string using the updateValue method.
 
To use this directive we have to associate with an element in the HTML as shown below.
                <input type=”number” ppNoZero />

        
 
Now include this directive in your module to import its functionality into your project.
 
Happy Coding.
 

About Author

Author Image
Pawanpreet Singh

Pawanpreet is an seasoned Project Manager with a wealth of knowledge in software development, specializing in frontend and mobile applications. He possesses a strong command of project management tools, including Jira, Trello, and others. With a proven track record, he has successfully overseen the delivery of multiple software development projects, managing budgets and large teams. Notable projects he has contributed to include TimeForge, Yogyata, Kairos, Veto, Inspirien App, and more. Pawanpreet excels in developing and maintaining project plans, schedules, and budgets, ensuring timely delivery while staying within allocated resources. He collaborates closely with clients to define project scope and requirements, establish timelines and milestones, and effectively manage expectations. Regular project status meetings are conducted by him, providing clients and stakeholders with consistent updates on project progress, risks, and issues. Additionally, he coaches and mentors project leads, offering guidance on project management best practices and supporting their professional development.

Request for Proposal

Name is required

Comment is required

Sending message..