【问题标题】:Why does the (change) function work only if I leave for first time?为什么(更改)功能仅在我第一次离开时才起作用?
【发布时间】:2022-01-05 10:13:07
【问题描述】:

我编写了这段代码来检查总单词是否至少为 3。当我输入少于 3 个单词并通过单击外部或选项卡离开文本框时,我会工作。但如果我第二次离开它没有命中,即没有错误,它只会在第一次工作。所以我必须再去一次,确保单词少于三个然后离开。如何解决?

countTotalWords() {
    let str= this.model.FullName_AR;
    
    if(!str) {
      return;
    }

    let totalWords= str.split(' ')
           .filter(function(n: string) 
           { 
             return n != '' 
           })
           .length;

      if(totalWords < 3)
      {
        this.wordCountAchieved= false;
        Swal.fire(
         'minimum 3 words',
         'input minimum 3 words',
         'error'
        )
      }
      else {
        this.wordCountAchieved= true;
      }
  }

html

 <input type="text" #nameArabic (change)="countTotalWords()" class="form-control" id="nameAR" [(ngModel)]="model.FullName_AR" name="nameAR" #name="ngModel" required>

【问题讨论】:

  • 您是否第二次编辑内容? change 仅在值更改时触发。也许改用blur

标签: javascript angular typescript


【解决方案1】:

尝试进行更改,看看第二轮会发生什么,因为只有在检测到内容发生更改时才会触发更改。

【讨论】:

    【解决方案2】:

    你需要使用改变的模糊事件

     <input type="text" #nameArabic (blur)="countTotalWords()">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-09
      • 1970-01-01
      • 1970-01-01
      • 2011-07-13
      • 2014-05-05
      • 2017-05-21
      • 1970-01-01
      相关资源
      最近更新 更多