我正在使用Angular2,我创建了一个将掩码放在输入上的指令,如下所示:
import {Directive, Attribute} from 'angular2/core';
import {NgModel} from 'angular2/common';
@Directive({
selector: '[real]',
host: {
'(blur)': 'onInputChange()'
}
})
export class RealDirective {
modelValue: string;
viewValue: string;
constructor(public model: NgModel) {
}
onInputChange() {
this.modelValue = this.model.value.replace(/[^0-9\,]/g,'');
this.viewValue = RealDirective.format(this.modelValue);
this.model.viewToModelUpdate(this.modelValue);
this.model.valueAccessor.writeValue(this.viewValue)
}
static format(valor) {
if (valor == "") {
valor = "0";
}
var valorFloat: number = parseFloat(valor.replace(",", "."));
var valorString: string = valorFloat.toFixed(2).toString().replace(".", ",");
var valorSemCasasDecimais = valorString.substring(0, valorString.length - 3);
var valorArray: string[] = valorSemCasasDecimais.split("");
var casa: number = 0;
var valorStringComPontosInvertida: string = "";
for (var i = valorArray.length - 1; i > -1; i--) {
valorStringComPontosInvertida = valorStringComPontosInvertida + valorArray[i];
casa = casa + 1;
if (casa == 3 && i > 0) {
valorStringComPontosInvertida = valorStringComPontosInvertida + ".";
casa = 0;
}
}
var valorStringComPontosInvertidaArray: string[] = valorStringComPontosInvertida.split("");
var valorStringComPontosCorreta: string = "";
for (var i = valorStringComPontosInvertidaArray.length - 1; i > -1; i--) {
valorStringComPontosCorreta = valorStringComPontosCorreta + valorStringComPontosInvertidaArray[i];
}
var valorStringPronta: string = valorStringComPontosCorreta + valorString.substring(valorString.length - 3, valorString.length);
return valorStringPronta;
}
}
它运行模糊事件。 但是我希望在每个输入的表单上加载信息时执行,有没有人知道如何做到这一点?
答案 0 :(得分:1)
您可以使用ngOnInit方法等待加载指令。 https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html
例如:
@Directive({
selector: '[real]',
host: {
'(blur)': 'onInputChange()'
}
})
export class RealDirective {
modelValue: string;
viewValue: string;
constructor(public model: NgModel) {
}
ngOnInit():void {
console.log(this.model);
}
}
如果this.model为null,您可以考虑使用ngOnChanges而不是ngOnInit来检查值何时发生变化。
您也可以在代码中发布如何调用该指令