Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 在邮政编码文本框中的5个字符后显示连字符-未按预期工作_Html_Typescript_Angular8 - Fatal编程技术网

Html 在邮政编码文本框中的5个字符后显示连字符-未按预期工作

Html 在邮政编码文本框中的5个字符后显示连字符-未按预期工作,html,typescript,angular8,Html,Typescript,Angular8,我需要在邮政编码文本框中的5个字符后显示连字符。输入超过5个字符时,将按预期显示连字符。但是,当用户手动输入连字符符号时,代码应自动删除手动添加的连字符。这不是预期的效果。手动添加的连字符不会被删除。当我在browser developer tools中调试typescript代码时,我可以看到额外的连字符已从属性“zipCode”中删除,但该更改并未反映在UI中 以下是typescript文件的代码: export class AppComponent { zipCode: stri

我需要在邮政编码文本框中的5个字符后显示连字符。输入超过5个字符时,将按预期显示连字符。但是,当用户手动输入连字符符号时,代码应自动删除手动添加的连字符。这不是预期的效果。手动添加的连字符不会被删除。当我在browser developer tools中调试typescript代码时,我可以看到额外的连字符已从属性“zipCode”中删除,但该更改并未反映在UI中

以下是typescript文件的代码:

export class AppComponent {  

  zipCode: string = '';

  public setValue(val: any) {
    if(val.indexOf('-') >= 0)
      val = val.replaceAll('-', '');
    if(val.length > 5)
      val = val.substr(0,5) + '-' + val.substr(5, val.length - 5);
    this.zipCode = val;
  }
}
以下是html文件的代码:

<input type="text" name="zipField" [(value)] = "zipCode" (input)="setValue($event.target.value)">


有人能告诉我为什么这个代码不起作用吗。此外,请建议任何替代方法来删除手动添加的额外连字符。提前感谢。

您应该传递元素本身,而不是只传递
输入的

这样,您也可以更改
input
标记中的文本

<input type="text" name="zipField" [(value)] = "zipCode" (input)="setValue($event.target)">
export class AppComponent {  
  ...

  public setValue(element: any) {
    let val = element.value;

    if(val.contains('-'))
      val = val.replaceAll('-', '');
    if(val.length > 5)
      val = val.substr(0,5) + '-' + val.substr(5, val.length - 5);

    this.zipCode = val;
    element.value = val;
  }
}