首页 > 解决方案 > 我需要对有角度的表单进行验证

问题描述

import {  FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
   ngOnInit() {
 
    this.createFormControls();
    this.createForm();
  }
  createFormControls(){
    
    this.firstName = new FormControl('',Validators.required);
    this.lastName= new FormControl('',Validators.required);
    this.Address= new FormControl('',Validators.required);
    this.age = new FormControl('',Validators.required);
    this.phnumer= new FormControl('',Validators.required);
  }
  createForm(){
    this.form = new FormGroup({
      name: new FormGroup({
      firstName:this.firstName,
      lastName: this.lastName,
      Address:this.Address,
      age:this.age,
      phnumer:this.phnumer
      }),
    });
  }

我需要在 angular6 中验证一个表单,我有 5 个字段,但是需要在没有提交按钮的情况下进行验证,我必须在同一个内联中验证它们。这是我在 ts 文件中的代码现在我已经在 html 页面中实现了验证,但是验证应该在同一行中显示错误消息,而不是单击提交按钮

标签: htmlcssangulartypescriptangular6

解决方案


您可以使用 Angular 中的内置验证器来实现这一点(https://angular.io/guide/form-validation#built-in-validators

get在您的组件中,创建一个表单组和一个 getter 方法,以通过父组中的方法访问表单控件。我将为单个字段提供一个示例。

createForm(){
    this.form = new FormGroup({
        firstName:  new FormControl('', Validators.required)
    });
}

get firstName() {
    return this.form.get('firstName');
}

在您的 HTML 中,您可以使用条件表达式和验证属性来显示错误。

<form [formGroup]="form">
    <label for="firstName">First Name
        <input id="firstName" formControlName="firstName">
        <div *ngIf="firstName.invalid && (firstName.dirty || firstName.touched)">
            <div *ngIf="firstName.errors.required">
                First Name is required.
            </div>
        </div>
    </label>
</form>

推荐阅读