离开输入控件时如何触发* ngIf指令进行验证

时间:2019-01-17 04:09:37

标签: angular angular-reactive-forms

我是Angular的新手,我正在制作一个反应式表格。

我在'em'标记上有一个* ngIf指令,该指令可验证Input text值是否有效,如果无效,则应将'em'标记注入HTML并显示“ Required”

<em *ngIf="!validateLastName()">Required</em>

每次将鼠标从Input控件移开时,如何才能获得* ngIf触发?

这是整个div:

<div class="form-group" [ngClass]="{'error' :!validateLastName()}">
          <label for="lastName">Last Name:</label>
          <em *ngIf="!validateLastName()">Required</em>
          <input formConrolName="lastName" id="lastName" type="text" 
          class="form-control" placeholder="Last Name..." />
        </div>

这是组件中的验证代码:

validateLastName(){ 
   return this.lastName.valid || this.lastName.untouched 
}

我正在参加有关Pluralsight的Angular课程(Angular基础知识) 由Jim Cooper和Joe Eames编写),课程作者在离开控件时可以在em标签上触发“ validateLastName()方法。我看不到他们在哪里有其他设置或代码导致进行验证,当他们离开输入导航时,它似乎会自动发生。

有什么想法吗?

这是此组件的完整HTML代码(profile.component.html):

<div>
    <h1>Edit Your Profile </h1>
    <hr>
    <div class="col-md-4">
      <form [formGroup]="profileForm" (ngSubmit)="saveProfile(profileForm.value)" 
      autocomplete="off" novalidate>
        <div class="form-group" [ngClass]="{'error' : !validateFirstName() }">
          <label for="firstName">First Name:</label>
          <em *ngIf="!validateFirstName()">Required</em>
          <input fromControlName="firstName" id="firstName" (blur)="validateLastName()" type="text" 
          class="form-control" placeholder="First Name..." />
        </div>
        <div class="form-group" [ngClass]="{'error' :!validateLastName()}">
          <label for="lastName">Last Name:</label>
          <em *ngIf="!validateLastName()">Required</em>
          <input formConrolName="lastName" id="lastName" type="text" 
          class="form-control" placeholder="Last Name..." />
        </div>

        <button type="submit" class="btn btn-primary">Save</button>
        <button type="button" (click)="cancel" class="btn btn-default">Cancel</button>
      </form>
    </div>
  </div>

以下是组件(profile.component.ts):

import { Component, OnInit } from '@angular/core'
import { FormControl, FormGroup, Validators } from '@angular/forms'; 
import { AuthService } from './auth.service'
import { Router } from "@angular/router"

@Component({
templateUrl: "./profile.component.html",
styles: [`
    em {float-right; color:#E05C65; padding-left: 10px;}
    .error input {background-color:#E3C3C5;}
    .error ::-webkit-input-placeholder { color: #999; }
    .error ::-moz-placeholder { color: #999 }
    .error :-moz-placeholder { color: #999 }
    .error :ms-input-placeholder { color: #999 }
 `]
})
export class ProfileComponent implements OnInit {
  profileForm:FormGroup
  private firstName:FormControl
  private lastName:FormControl 
  constructor(private auth:AuthService, private router:Router){ 
  }

  ngOnInit(){  
     this.firstName = new FormControl(
      this.auth.currentUser.firstName, Validators.required) 

    this.lastName = new FormControl(
      this.auth.currentUser.lastName, Validators.required) 

      this.profileForm = new FormGroup({
      firstName: this.firstName,
      lastName: this.lastName

    })  
  }

  saveProfile(formValues){
    console.log("Form is valid: " + this.profileForm.valid)
    if (this.profileForm.valid){
      this.auth.updateCurrentUser(formValues.firstName.value,             
       formValues.lastName.value)
      this.router.navigate(["events"])
    } 
  }

  validateFirstName(){ 
    console.log("Is Valid: " + (this.firstName.valid ||         
    this.firstName.untouched))
    return this.firstName.valid || this.firstName.untouched 
  }

  validateLastName(){ 
    return this.lastName.valid || this.lastName.untouched 
  }

  cancel(){
    this.router.navigate(["events"])
  }
}

3 个答案:

答案 0 :(得分:2)

有适当的方法来处理您的案件,这里是runnable demo

双向绑定

<em *ngIf="!isLastNameValid()">Required</em>
   <br />
   <input type="text" [(ngModel)]="value"/>

  value = "Cattie";
  isLastNameValid() {
    return this.value === "Cattie";
  }

听模糊事件

   <em *ngIf="!isValid">Required</em>
   <br />
   <input type="text" #myInput (blur)="validateName(myInput.value)"/>

  isValid = false;
  validateName(value: string) {
    this.isValid = value === "Cattie";
  }

答案 1 :(得分:1)

这可以帮助:“ mouseleave”事件

<input formConrolName="lastName" id="lastName" type="text" 
          class="form-control" (mouseleave)="validateLastName()" placeholder="Last Name..." />

编辑:根据您的Angular版本,您可能需要尝试:

(mouseout)="validateLastName()"

答案 2 :(得分:0)

您可以简单地使用表单方法,而不用像这样调用组件方法。

<em *ngIf="profileForm.get('firstName').invalid && profileForm.get('firstName').dirty">Required</em>

每个控件有多个标志,例如有效,无效,原始,已触摸等。您可以直接在HTML模板中使用这些标志,而不用调用组件方法来验证字段。