【问题标题】:Angular X directive: the best way to handle ngModel value changeAngular X 指令:处理 ngModel 值变化的最佳方式
【发布时间】:2018-08-14 16:20:22
【问题描述】:

我有这样的指令,它处理 onBlur/onFocus 的变化并将$符号添加到输入值的开头:

@Directive({
  selector: "[inputChanger]",
  host: {
    "(focus)": "onFocus($event)",
    "(blur)": "onBlur($event)"
  }
})
export class InputChangerDirective implements OnChanges {
  @Input("inputChanger") type: string;

  @Input() serverValue: string;

  constructor(private model: NgModel, private el: ElementRef) {}

  ngOnChanges(changes) {
    if (changes.serverValue && changes.serverValue.currentValue) {
      setTimeout(() => {
        this.el.nativeElement.dispatchEvent(new Event("blur"));
      });
    }
  }

  onFocus(element: any) {
    element.target.value = this.model.model || "";
  }

  onBlur(element: any) {
    if (Number(this.model.model)) {
      element.target.value = "$" + Number(this.model.model);
    }
  }
}

当我blur 我的输入或来自服务器的数据来时,我需要以某种方式添加这个$... 我做的有点棘手...我添加了一个新输入serverValue,它等于服务器响应value,并在指令中收听它。

但我认为这是一种不好的方式。

也许有更好的方法来填充输入、监听 ngModel 的变化并格式化它?

你可以在这里查看我的沙盒:https://codesandbox.io/s/18qlqny42q 清楚地了解我要做什么...

【问题讨论】:

标签: angular angular2-directives


【解决方案1】:

您可以使用管道来格式化输入值。像这样的

<input type="text" (ngModel)="model" [value]="text | pipe" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-27
    • 2013-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多