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.