修剪空格的角度自定义指令有效,但验证失败

问题描述 投票:0回答:1

在我的ionic3角度应用程序中,我需要在用户输入时修剪电子邮件输入字段中的空格。为此,我创建了一个这样的指令:

    @Directive({
  selector: '[no-space]',
  host: {
    "(input)": 'onInputChange($event)'
  }
})
export class NoSpaceDirective{
  onInputChange($event){
    $event.target.value = $event.target.value.trim();
  }
}

该指令有效,但验证行为不正确:验证设置为不允许值中的空格;当我键入一个空格时,它会被指令修剪,但验证失败,好像空间不可见但仍然存在。

angular ionic-framework trim angular-directive
1个回答
0
投票

优化问题的解决方案是阻止用户键入空格,我们可以使用以下代码实现。

@Directive({
  selector: '[no-space]',
  host: {
    "(input)": 'onInputChange($event)'
  }
})
export class NoSpaceDirective{
  if ($event.key === ' ' || $event.key === 'Spacebar') {
    // ' ' is standard, 'Spacebar' was used by IE9 and Firefox < 37
    return false; //preventing type space character
    console.log('Space pressed')
  } else {
      return true; 
}

希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.