繁体   English   中英

在Angular 2中进行数据绑定后如何执行动作?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM