当前位置: 首页 > 工具软件 > FormBuilder > 使用案例 >

使用Angular FormBuilder初始化新建FormGroup

程振濂
2023-12-01

FormBuilder可以帮助我们简单优雅的新建FromGroup,并且允许对每个controller设置验证规则。本文将展示其基本用法。
首先让我们对比FormBuilder与传统方法,以展示其优越性
传统方法:

validateForm = new FormGroup({
    firstname: new FormControl(null, [Validators.required]),
    lastname: new FormControl(null, [Validators.required]),
    email: new FormControl(null, [Validators.required])
  });

使用FormBuilder:

this.contactForm = this.formBuilder.group({
  firstname: [null, [Validators.required]],
  lastname: [null, [Validators.required]],
  email: [null, [Validators.required]]
});

使用方法

  1. 导入
import { FormBuilder } from '@angular/forms'
  1. 依赖注入
constructor(private formBuilder: FormBuilder) {
}
  1. 使用
this.contactForm = this.formBuilder.group({
  firstname: [''],
  lastname: [''],
  email: [''],
  gender: [''],
  isMarried: [''],
  country: [''],
});

也可以添加一个或多个验证规则(validatiors)

this.contactForm = this.formBuilder.group({
  firstname: ['', [Validators.required, Validators.minLength(10)]],
  lastname: ['', [Validators.required, Validators.maxLength(15), Validators.pattern("^[a-zA-Z]+$")]],
  email: ['', [Validators.required, Validators.email]],
  gender: ['', [Validators.required]],
  isMarried: ['', [Validators.required]],
  country: ['', [Validators.required]],
});

快快用起来吧!

 类似资料: