简体   繁体   English

为什么(更改)function 只有在我第一次离开时才有效?

[英]Why does the (change) function work only if I leave for first time?

I have written this code to check if the total words are atleast 3. I tworks when I put less than 3 words and leave text box by clicking outside or tab.我编写了这段代码来检查总单词是否至少为 3。当我输入少于 3 个单词并通过单击外部或选项卡离开文本框时,我会工作。 but it only works first time if I leave 2nd time it doesn't hit ie no error.但它只有在我第二次离开时才有效,即没有错误。 So i have to go again and make sure words are less than three and leave.所以我必须再次 go 并确保单词少于三个并离开。 How to fix it?如何解决?

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 html

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

Try making a change and see what happens the second time round because change only triggered when it detects a change to the content.尝试进行更改并查看第二次会发生什么,因为更改仅在检测到内容更改时触发。

you need to use blur event insted of change你需要使用改变的模糊事件

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM