【发布时间】:2017-05-11 15:42:35
【问题描述】:
我正在开发一个 Angular 2 SPA。我的申请由以下人员组成:
- 一个组件
- 一个指令
我已经构建了一个指令,它使用 onfocus 和 onblur 事件格式化文本输入。在焦点事件中删除点到文本值,在模糊事件中添加千点到文本值。
以下组件代码:
<div>
<input id="input" [(ngModel)]="numero" InputNumber />
</div>
以下组件的 TypeScript 代码:
import { Component } from '@angular/core';
@Component({
selector: 'counter',
templateUrl: './counter.component.html'
})
export class CounterComponent {
numero: number;
public incrementCounter() {
}
ngOnInit() {
this.numero = 100100100;
}
}
以下指令的 TypeScript 代码:
import { Directive, HostListener, ElementRef, OnInit } from "@angular/core";
@Directive({ selector: "[InputNumber]" })
export class InputNumber implements OnInit, OnChanges {
private el: HTMLInputElement;
constructor(private elementRef: ElementRef) {
this.el = this.elementRef.nativeElement;
}
ngOnInit(): void {
// this.el.value is empty
console.log("Init " + this.el.value);
this.el.value = this.numberWithCommas(this.el.value);
}
ngOnChanges(changes: any): void {
// OnChanging value this code is not executed...
console.log("Change " + this.el.value);
this.el.value = this.numberWithCommas(this.el.value);
}
@HostListener("focus", ["$event.target.value"])
onFocus(value: string) {
this.el.value = this.replaceAll(value, ".", "");
}
@HostListener("blur", ["$event.target.value"])
onBlur(value: string) {
this.el.value = this.numberWithCommas(value);
}
private numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}
private escapeRegExp(str) {
return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
private replaceAll(str, find, replace) {
return str.replace(new RegExp(this.escapeRegExp(find), 'g'), replace);
}
}
以下代码有效,但我需要失去焦点才能显示我的号码,如“100.100.100”。如何在初始化数据加载时执行此操作?
我在此链接添加一个示例:Plnkr example
谢谢
【问题讨论】:
-
你的意思是
ngOnInit() {this.el.value = this.numberWithCommas(this.el.value);}?它将在默认输入状态下设置格式。 -
嗨,我试过 ngOnInit 但 this.el.value 是空的。现在我更新问题。谢谢
-
尝试在
ngOnChanges(){}上做同样的事情 -
您好Leguest,我已经更新了这个问题。我试过了,但没有引发事件...
标签: javascript typescript angular2-directives