Monday, November 26, 2018

Passing values to Custom Attribute Directive

In the Highlighter directive custom attribute directive example we saw how to create a custom attribute directive and use it in a component. In the Highlighter directive example we just had to add the directive name in the HTML element and that’s it the directive used ElementRef to get a handle of the DOM element and set the background color of the element.

There are cases where we want to pass some values from the HTML element to the directive to perform more meaningful operations in the directive. To pass values to the Directive class we have to declare the parameters as @Input in the directive class as follows.

export class ExpValidatorDirective implements OnChanges  {
  @Input() expression: string
  ...
}

And when using the directive in the Component, we can pass values to the directive like properties as follows.

<span expValidator [expression]="value to be passed to the Directive"> </span>

In the following example we will create an Expression validator directive, this directive will take 2 parameters the first one is a regular expression and the second one is the value to evaluate. 

The expression validator will validate the value passed with the expression (Regular expression) and change the background color of the element based on the result of the evaluation. If the value passed matches the expression then it sets a green color and a test “valid”, id the value does not match the expression it sets a red color and a text “InValid”.

Expression validator directive
import { Directive, Input, OnChanges, ElementRef  } from '@angular/core';
@Directive({
  selector: '[expValidator]'
})

export class ExpValidatorDirective implements OnChanges  {
  @Input() expression: string
  @Input() value: string
  constructor(private elRef: ElementRef) { }

  ngOnChanges() {
    var reg = new RegExp(this.expression);
    if(reg.test(this.value)) {
      this.elRef.nativeElement.style.backgroundColor = "#aaffaa";
      this.elRef.nativeElement.innerText = 'Valid';
    } else {
      this.elRef.nativeElement.style.backgroundColor = "#ffaaaa";
      this.elRef.nativeElement.innerText = 'InValid';
    }   
  }
}

Component using the Directive
<div style="text-align:center">
    <h1>
      <input type="text" [(ngModel)]="name"/> 
      <span expValidator [expression]="'^[0-9]+$'" [value] = "name" [ngClass]="'label'"> </span>
    </h1> 
</div>

In the above sample we are passing an expression which matches only Numbers, when the value entered in the textbox is a number then the expression is valid, any non-numeric value is invalid.

The final output will be as follows.

Search Flipkart Products:
Flipkart.com

No comments: