我正在创建一个自定义指令,它应该重新格式化md-输入中的文本。在我的指令ngOnInit和@HostListener('blur','$event.target.value')中,我有一个逻辑来重新格式化用户输入的文本。而且它是工作的,除非数据是从api调用中绑定的。我想知道,当角更新数据时,会触发什么事件,这样我就可以在指令中侦听它,并为该数据启动我的格式逻辑。
更新1:添加了代码来清理事物
<input type="text"
mdInput
[(ngModel)]="item.Price"
appMyPriceFormatter
placeholder="Price"
tabindex="5"
[disabled]="disableInputs">指令代码:
import {Directive, ElementRef, HostListener, OnInit} from '@angular/core';
import {CurrencyPipe} from '@angular/common';
@Directive({
selector: '[appMyPriceFormatter]'
})
export class MyPriceFormatterDirective implements OnInit {
private el: HTMLInputElement;
constructor(private elementRef: ElementRef,
private currencyPipe: CurrencyPipe) {
this.el = this.elementRef.nativeElement;
}
ngOnInit() {
if ((this.el.value !== null) && (this.el.value.trim() !== '')) {
this.el.value = this.currencyPipe.transform(this.el.value, 'USD', true, '1.5-5');
} else {
this.el.value = null;
}
}
@HostListener('focus', ['$event.target.value'])
onFocus(value) {
this.el.value = value.replace(/[^\d\-\.]/g, '');
}
@HostListener('blur', ['$event.target.value'])
onBlur(value) {
if ((value !== null) && (value.trim() !== '')) {
this.el.value = this.currencyPipe.transform(value, 'USD', true, '1.5-5');
} else {
this.el.value = null;
}
}
}发布于 2017-10-11 19:00:03
显然,我可以使用ngModel的货币来实现这一点,并在ngModelChange的处理程序中做一些棘手的事情,但是这意味着在每个字段的每个页面上,我都需要有一个单独的函数等等。此外,我使用货币管道只是为了例子,在现实中,我正在做一些更棘手的事情。考虑到这一点,我不希望这个逻辑扩展到多个函数和组件,因此我最终进一步调整了我的指令。
在深入了解了生命周期事件之后,ngDoCheck ( https://angular.io/guide/lifecycle-hooks )似乎就能做到这一点。我需要注意的唯一部分是在用户输入时的递归保护和防止格式化的保护,因此我最后得到了如下内容:
ngDoCheck() {
if (this.focused) {
return;
}
this.el.value = this.formatValue(this.el.value);
}发布于 2017-10-10 14:40:15
我认为,如果您在指令中侦听ngModelChange事件,您应该能够异步地获取发生在输入字段上的更改。
所以在你的指令里,
@HostListener('ngModelChange', ['$event'])
onInputFieldChange(value) {
// logic for handling the change
}有关这事件的更多信息,请参见ngModelChange。
https://stackoverflow.com/questions/46655774
复制相似问题