如何使用指令将事件添加到 Angular 5 应用中的输入?
How to add event to input in Angular 5 app using directive?
我有以下指令 groupingFormat
对输入文本执行分组
当用户向上键时:
@Directive({
selector: '[groupingFormat]'
})
export class GroupingFormatDirective {
private el: HTMLInputElement;
constructor(elRef: ElementRef) {
this.el = elRef.nativeElement;
}
ngAfterViewInit(): void {
let elem : HTMLInputElement = this.el;
elem.addEventListener('keyup',() => {
this.el.value = this.digitGrouping(this.el.value);
});
}
}
用法示例:
<input type="text" #myValue="ngModel" name="my_value" [(ngModel)]="myObj.myValue" id="my_value" required groupingFormat>
该指令按预期工作,但现在我有新要求:输入
text 也应该在页面加载时使用该指令,如果是表单
在页面内打开,输入变为可见。
是否有一种简单的方法来更新指令以支持此功能或
任何替代解决方案?附加另一个指令?
谢谢
<input type="text" name="my_value" [appInputevent]="myValue" [(ngModel)]="myValue">
指令文件
import { Directive,HostListener,ElementRef, Input } from '@angular/core';
@Directive({
selector: '[appInputevent]'
})
export class InputeventDirective {
constructor(private el:ElementRef) { }
@Input('appInputevent') params: string;
@HostListener('keyup', ['$event'])
onKeyUp(event: KeyboardEvent) {
console.log('got parameters: '+this.params);
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
根据需要更改 hostlistner 事件。
演示用-- https://stackblitz.com/edit/ionic2-test?file=app%2Finputevent.directive.ts
我有以下指令 groupingFormat
对输入文本执行分组
当用户向上键时:
@Directive({
selector: '[groupingFormat]'
})
export class GroupingFormatDirective {
private el: HTMLInputElement;
constructor(elRef: ElementRef) {
this.el = elRef.nativeElement;
}
ngAfterViewInit(): void {
let elem : HTMLInputElement = this.el;
elem.addEventListener('keyup',() => {
this.el.value = this.digitGrouping(this.el.value);
});
}
}
用法示例:
<input type="text" #myValue="ngModel" name="my_value" [(ngModel)]="myObj.myValue" id="my_value" required groupingFormat>
该指令按预期工作,但现在我有新要求:输入 text 也应该在页面加载时使用该指令,如果是表单 在页面内打开,输入变为可见。
是否有一种简单的方法来更新指令以支持此功能或 任何替代解决方案?附加另一个指令? 谢谢
<input type="text" name="my_value" [appInputevent]="myValue" [(ngModel)]="myValue">
指令文件
import { Directive,HostListener,ElementRef, Input } from '@angular/core';
@Directive({
selector: '[appInputevent]'
})
export class InputeventDirective {
constructor(private el:ElementRef) { }
@Input('appInputevent') params: string;
@HostListener('keyup', ['$event'])
onKeyUp(event: KeyboardEvent) {
console.log('got parameters: '+this.params);
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
根据需要更改 hostlistner 事件。
演示用-- https://stackblitz.com/edit/ionic2-test?file=app%2Finputevent.directive.ts