0

我目前正在使用 HostListener 以便能够在用户键入用户文本的同时格式化用户文本。例如,如果用户正在输入电话号码,我希望能够根据需要添加格式。如果字符串为 0000,我希望文本为 000-0,如果文本为 0000000000,则为“(801) 123 - 1234”。我有这样做的逻辑,但我目前正在使用主机监听器来执行此操作。

  @HostListener("textChange")
  public onTextChange(target): void {
    this.el.text = this.phoneFormatPipe.transform(this.el.text)
  }

这可行,但它会一直调用自己,直到达到最大堆栈调用限制。这显然太慢了,所以我的问题是:如何在不触发 textChange 事件的情况下修改元素内的文本?还是有其他方法可以做到这一点?

提前致谢!快乐编码!

4

2 回答 2

2

There is a better way to do what you're doing, but I'm not sure if there's an even better way. Coming from iOS development, I know there is definitely a more appropriate place to do this sort of manipulation, but doing it here shouldn't be causing you to reach the max stack.

If you update your source to do this instead, you will avoid the maximum stack limit (and significantly increase performance of your app). It is not the best way, but it is the best way that I have found available in NativeScript at this time.

@HostListener("textChange")
public onTextChange(target): void {
  let newText: string = this.phoneFormatPipe.transform(this.el.text);
  if (this.el.text !== newText) {
    this.el.text = newText;
  }
}
于 2018-11-19T19:19:50.660 回答
0

它将是递归的,直到您确保它不是带有 if 条件的相同字符串,就像在@Ian 的示例中一样。

此外,我建议检查nativescript-masked-text-field而不是在每次更改时手动格式化文本。

于 2018-11-19T19:35:49.293 回答