【问题标题】:How can I execute action after data-bind in Angular 2?如何在 Angular 2 中进行数据绑定后执行操作?
【发布时间】: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


【解决方案1】:

您可以使用 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] 上应用管道并使用 Angular 事件 (focus)(focusout) 来更改你的变量。

<input [ngModel]="numero | dots : hasFocus" (focus)="hasFocus=true" (focusout)="hasFocus=false" (ngModelChange)="numero=$event" />

【讨论】:

    【解决方案2】:

    我认为你的指令应该实现 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;
    }
    

    【讨论】:

    • 嗨 proJS。我试过使用 ControlValueAccessor,但我从来没有使用过这个 Angular 的元素。请问,如果可以的话,我可以举一个例子吗?我在问题上添加了一个 Plnkr。谢谢
    猜你喜欢
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多