Suppose there is such a requirement: we need to enhance the native input tag in HTML so that it can achieve the effect of automatically switching its color as the user inputs characters.
This is a typical requirement that can be implemented using Angular Directive.
Every Directive has a host element.
Decorator that marks a DOM property as a host-binding property and supplies configuration metadata. Angular automatically checks host property bindings during change detection, and if a binding changes it updates the host element of the directive.
In Directive, modifying the Directive attribute modified by @HostBinding is equivalent to modifying the attribute of the DOM element itself.
In the same way, the event handling function decorated by @HostListener will be automatically triggered after the corresponding event occurs on the host element.
The complete implementation code of Rainbow instruction:
import { Directive, HostBinding, HostListener } from '@angular/core';
@Directive({
selector: '[appRainbow]'
})
export class RainbowDirective{
possibleColors = [
'darksalmon', 'hotpink', 'lightskyblue', 'goldenrod', 'peachpuff',
'mediumspringgreen', 'cornflowerblue', 'blanchedalmond', 'lightslategrey'
];
@HostBinding('style.color') color: string;
@HostBinding('style.borderColor') borderColor: string;
@HostListener('keydown') onKeydown(){
const colorPick = Math.floor(Math.random() * this.possibleColors.length);
console.log('Jerry colorPick: ' + colorPick);
this.color = this.borderColor = this.possibleColors[colorPick];
}
}
The way to consume this instruction is very simple:
The final effect: as I enter the field in the input field, the input font color automatically changes.
For the complete code, refer to my 160c37a7ba62de Github
More original articles by Jerry, all in: "Wang Zixi":
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。