[英]How can I execute action after data-bind in Angular 2?
我正在開發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示例
謝謝
我認為您的指令應實現ControlValueAccessor接口https://angular.io/docs/ts/latest/api/forms/index/ControlValueAccessor-interface.html在您的指令中編寫模型是必需的。 ControlValueAccessor接口具有將首先調用的writeValue(value: any)
方法。 因此,您的writeValue方法將如下所示:
private onChange: (_: any) => {};
...
writeValue(val) {
const editedValue = this.numberWithCommas(val);
this._onChange(val);
}
registerOnChange(fn: any) : void {
this._onChange = fn;
}
您可以通過使用Pipe來執行此操作,該Pipe接受代表您的焦點/非焦點動作的布爾參數。
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'dots'})
export class DotsPipe implements PipeTransform {
transform(value: number, hasFocus:boolean): any {
if(hasFocus){
return value.toString().replace(/\./g,'');
}else{
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}
}
}
然后,您必須在[ngModel]
上應用Pipe並使用Angular事件(focus)
和(focusout)
來更改變量。
<input [ngModel]="numero | dots : hasFocus" (focus)="hasFocus=true" (focusout)="hasFocus=false" (ngModelChange)="numero=$event" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.