在Angular 4 Reactive Forms中提交验证消息

问题描述:

我正在使用Angular 4,Reactive forms。我想在用户单击Submit/Create Account按钮时显示验证错误消息。 这是我正在使用的HTML和typescript代码。在Angular 4 Reactive Forms中提交验证消息

<form [formGroup]="signupForm" (ngSubmit)="onSubmit()"> 

    <div class="form-group"> 
    <input type="text" 
      id="firstname" 
      name="firstname" 
      formControlName="firstname" 
      placeholder="First Name"> 
    <span *ngIf="!signupForm.get('firstname').valid && signupForm.get('firstname').touched" 
      class="help-block"> Please Enter First Name (Minimum 2 Characters)</span> 
    </div> 

    <div class="form-group"> 
    <input type="text" 
      id="lastname" 
      name="lastname" 
      formControlName="lastname" 
      placeholder="Last Name"> 
    <span *ngIf="!signupForm.get('lastname').valid && signupForm.get('lastname').touched" 
      class="help-block"> Please Enter Last Name (Minimum 2 Characters)</span> 
    </div> 

    <div class="form-group"> 
    <button type="submit" 
      class="btn btn-success btn-lg btn-qte">Create Account</button> 
    </div> 

</form> 

TYPE脚本代码


export class UserRegistrationComponent implements OnInit { 
    signupForm: FormGroup; 

    ngOnInit() { 
     this.signupForm = new FormGroup({ 
      'firstname': new FormControl(null, [Validators.required, Validators.minLength(2)]), 
      'lastname': new FormControl(null, [Validators.required, Validators.minLength(2),]), 
      'businessname': new FormControl(null), 
      'phonenumber': new FormControl(null, [Validators.required]), 
      'email': new FormControl(null, [Validators.required, Validators.email]), 
      'password': new FormControl(null, [Validators.required]), 
      'confirmpassword': new FormControl(null, Validators.required) 

     }); 
    } 

    onSubmit() { 
     console.log(this.signupForm) 
    } 

} 

喜欢的东西

onSubmit() { 
    console.log(this.signupForm) 
    this.signupForm.controls['firstname'].markAsTouched() 
} 

要通过012获得像toucheddirtyvalid表单控件的属性使用:

signupForm.controls.firstname.touched。同样的方式你可以得到其他属性,如有效和无效。

如果您创建了FormControl的单个对象,则可以在不使用formGroup的情况下访问对象属性firstname.touched

有关模型驱动表单验证的更多信息,请参阅Model Driven Form Validations