簡體   English   中英

修剪空間的角度自定義指令有效,但驗證失敗

[英]angular custom directive to trim spaces works but validation fails

在我的ionic3 angular應用程序中,我需要在用戶鍵入時從電子郵件輸入字段中修剪空格。 為此,我創建了這樣的指令:

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

該指令有效,但是驗證的行為不正確:驗證設置為不允許在值中包含空格; 當我鍵入一個空格時,它會被偽指令修剪掉,但驗證失敗,好像該空格不可見但仍然存在。

要優化解決您的問題的方法是防止用戶鍵入空格,我們可以使用以下代碼來實現。

@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; 
}

希望這會有所幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM