带有邮件检查的 Angular5 反应式表单.js



下面是表单的HTML代码

<div class="form-group">
                <label for="email">Email</label>
     <input type="email" class="form-control" 
     (blur)="suggestEmail(signupForm.controls['userData'].controls.email.value)"
     id="email" formControlName="email">

     <span class="help-block" *ngIf="!signupForm.get('userData.email').valid && signupForm.get('userData.email').touched">
      please enter a valid email id 
     </span>
  </div>

下面是 ts 代码

constructor(private fb: FormBuilder) {
    this.signupForm = this.fb.group({
      userData: this.fb.group({
        email: [null, [Validators.required, Validators.email]]
      })
    });
  }
  ngOnInit() {
  }
  suggestEmail(email) {
    Mailcheck.run({
      email: email,
      domains: ['gmail.com', 'aol.com', 'hotmail.com', 'yahoo.com', 'rediffmail.com', 'edu', 'msn.com',], 
      secondLevelDomains: ['domain', 'hotmail'], 
      topLevelDomains: ["com", "net", "org", "info"],
      suggested: function (suggestion) {
        console.log(suggestion);
        if (suggestion) {
          alert(suggestion.full);
         console.log(suggestion.full + "dkdjdekjekde")
        }
      },
      empty: function () {
      }
    });
  }

现在,如果调用suggestions.full值,则会发出警报。但我正在尝试在 html 端显示suggestions.full,例如作为错误警告。

以下是我的堆栈闪电战的链接stackblitz

为了避免在

Mailcheck.run suggested回调中访问this的潜在问题,您可以保存 Mailcheck.run 的结果,检查它们,并在适当的情况下在表单字段上设置错误。

let check = Mailcheck.run({
   email: email,
   ... other stuff ...
   suggested: (suggestion) => {
     return suggestion;
   },
   empty: () => {
     return false; // or however you want to handle it...
   }
if (check && check.full) {
  this.suggestedEmail = check.full;
  this.signupForm.get('userData.email').setErrors({ 'has_suggestion': true })
}
// then in your template (using a getter)
<span class="help-block" 
      *ngIf="f.invalid && f.touched && f.errors?.has_suggestion">
  Suggestion: {{suggestedEmail}}
</span>

请找到这个堆栈闪电战 - 希望它有所帮助!

而不是使用常规function,该将丢失this范围arrow而函数会跟踪this。在此处阅读有关差异的更多信息 https://stackoverflow.com/a/34361380/5836034

做这样的事情

....
suggestion: any;
....
suggestEmail(email) {
   Mailcheck.run({
      email: email,
      domains: ['gmail.com', 'aol.com', 'hotmail.com', 'yahoo.com', 'rediffmail.com', 'edu', 'msn.com',], 
      secondLevelDomains: ['domain', 'hotmail'], 
      topLevelDomains: ["com", "net", "org", "info"],
      suggested: (suggestion) => {
        console.log(suggestion);
        if (suggestion) {
          alert(suggestion.full);
         this.suggestion = suggestion; 
         console.log(suggestion.full + "dkdjdekjekde")
        }
      },
      empty: function () {
      }
    });
}

观察箭头函数的使用,以跟踪this范围,并通过以下方式将suggestion的值分配给类变量

这个建议=建议

在您的模板中,您现在可以访问这样的suggestion

<div *ngIf="suggestion">{{suggestion.full}} </div>

来源: https://stackblitz.com/edit/angular-email-checker-bjcrcc

最新更新