我创建了一个简单的指令来修剪我的输入文本(我打算稍后扩展它的功能-因此请不要推荐简单的onkeyup函数),我想使该指令起作用。
我这样使用我的指令:
<input type="text" class="form-control" inputTextFilter [(ngModel)]="data.name">
我的指令如下:
import { Directive, HostBinding, HostListener } from '@angular/core';
@Directive({
selector: '[inputTextFilter]'
})
export class InputTextFilterDirective {
value: string;
constructor() {
console.log('contrusted InputTextFilterDirective');
this.value = '';
}
@HostListener('change')
onChange($event) {
console.log('in change InputTextFilterDirective');
this.value = $event.target.value.trim();
console.log(this.value);
}
}
我看到构造函数消息记录到窗口,但是on change消息从未出现,并且我的值也从未改变(未从末端开始修剪空格)。我怀疑hostListeners和hostProperties是不正确的,因为我已经看到了许多相互矛盾的示例……但是无法确认正确的方法。
这怎么了
将您的指令更改为
import { Directive, HostBinding, HostListener, ElementRef } from '@angular/core';
@Directive({
selector: '[inputTextFilter]'
})
export class InputTextFilterDirective {
@Input() ngModel: string;
constructor(private el: ElementRef) {
console.log('constructed InputTextFilterDirective');
(el.nativeElement as HTMLInputElement).value = '';
}
@HostListener('change')
onChange() {
console.log('in change InputTextFilterDirective');
(el.nativeElement as HTMLInputElement).value.trim();
console.log(this.ngModel);
}
}
尝试看看是否可行。如果不是,请尝试将事件从“ change
”更改为“ input
”或“ ngModelChange
”
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句