【发布时间】:2018-08-14 16:20:22
【问题描述】:
我有这样的指令,它处理 onBlur/onFocus 的变化并将$符号添加到输入值的开头:
@Directive({
selector: "[inputChanger]",
host: {
"(focus)": "onFocus($event)",
"(blur)": "onBlur($event)"
}
})
export class InputChangerDirective implements OnChanges {
@Input("inputChanger") type: string;
@Input() serverValue: string;
constructor(private model: NgModel, private el: ElementRef) {}
ngOnChanges(changes) {
if (changes.serverValue && changes.serverValue.currentValue) {
setTimeout(() => {
this.el.nativeElement.dispatchEvent(new Event("blur"));
});
}
}
onFocus(element: any) {
element.target.value = this.model.model || "";
}
onBlur(element: any) {
if (Number(this.model.model)) {
element.target.value = "$" + Number(this.model.model);
}
}
}
当我blur 我的输入或来自服务器的数据来时,我需要以某种方式添加这个$...
我做的有点棘手...我添加了一个新输入serverValue,它等于服务器响应value,并在指令中收听它。
但我认为这是一种不好的方式。
也许有更好的方法来填充输入、监听 ngModel 的变化并格式化它?
你可以在这里查看我的沙盒:https://codesandbox.io/s/18qlqny42q 清楚地了解我要做什么...
【问题讨论】:
-
为什么不使用过滤器/管道,当您收到响应时,通过管道运行值。
-
@alphapilgrim 因为我不必更改 ngModel 的值,只需更改表示形式
-
@alphapilgrim 不是!这不是 AngularJS
-
虽然它不是 Angular js,但该指令的代码仍然具有价值。你质疑标题字面意思是 ngModel 值变化。
标签: angular angular2-directives