angular7 FormGroup基本使用

在项目中使用Materail中Stepper组件, 需要进行跳转限制使用到 stepControl 绑定表单, 所以对FormGroup的基本使用进行了整理记录~

基本使用

  1. 需要引入相关模块
// 引入相关模块
import {FormArray, FormBuilder, FormGroup, Validators} from '@angular/forms';
// 注入FormBuilder
constructor(
    private formBuilder: FormBuilder
) {}
复制代码
  1. 声明/创建表单Group
checkRuleArr = [this.formBuilder.group({
    dataSource: ['param', Validators.required],
    keyword: [''],
    regx: ['']
})];
requestInfoForm: FormGroup;
// checkRuleArr: this.formBuilder.array(this.checkRuleArr),
// 这里checkRuleArr表示子表单, 验证方式可以是formBuilder.array数组 [是伪数组] 
// 可以通过get('0')方式获取到对应的验证方式
this.requestInfoForm = this.formBuilder.group({
    path: ['', Validators.required],
    method: ['POST', Validators.required],
    checkRuleArr: this.formBuilder.array(this.checkRuleArr),
    weightCtr: [false],
});
复制代码
  1. 表单的动态操作
// 首先要获取到可以动态操作的Control
get checkRuleArrForm(): FormArray {
    return this.requestInfoForm.get('checkRuleArr') as FormArray;
}
// 增, 一般是点击按钮...首先阻止默认操作
addCheckRule(e) {
    e.preventDefault();
    // 直接操作获取到的Control => 会直接更新到对应的FormGroup中
    this.checkRuleArrForm.push(this.formBuilder.group({
      	dataSource: ['param', Validators.required],
      	keyword: '',
      	regx: ''
    }));
}
// 删, 一般是点击按钮...首先阻止默认操作
delCheckRule(e, index) {
    e.preventDefault();
    // 通过removeAt方式删除对应位置的内容
    this.checkRuleArrForm.removeAt(index);
}
// 改 
// patchValue => 更新对应的值(部分更新)
this.requestInfoForm.patchValue({
    path: this.requestInfo.path,
    method: this.requestInfo.method,
    weightCtr: this.requestInfo.weightCtr,
})
// setValue => 更新对应的值(全部更新, 否则报错)
this.requestInfoForm.patchValue({
    path: this.requestInfo.path,
    method: this.requestInfo.method,
    weightCtr: this.requestInfo.weightCtr,
    checkRuleArr: this.formBuilder.array(this.checkRuleArr)
})
// 查 => 获取表单所有数据
this.requestInfoForm.value
// 如果要进行遍历需要将伪数组转化为真数组
toArray(arr) {
    return Array.from(arr);
}
// 监听表单内容变化
formValueChange(form: FormGroup) {
    form.valueChanges.subscribe(res => {
      this.getRequestInfo.emit(this.requestInfoForm);
    });
}

// 对group中的control进行增删改 => addControl / removeControl / setControl
addControl(name: string, control: AbstractControl): void;
removeControl(name: string): void;
setControl(name: string, control: AbstractControl): void;
复制代码

对应的html

<form [formGroup]="requestInfoForm">
    <mat-form-field>
        <input matInput placeholder="请求Path" formControlName="path" required>
        <mat-error>请求Path必填mat-error>
    mat-form-field>
    <mat-form-field>
        <mat-select placeholder="方法( Method )" formControlName="method">
          	<mat-option *ngFor="let method of methodArr" [value]="method.value">
            	{{method.viewValue}}
          	mat-option>
        mat-select>
    mat-form-field>
    
    <ul class="rule-list" *ngIf="requestInfo.checkRuleArr.length > 0">
      	<li *ngFor="let checkRule of toArray(checkRuleArrForm); let i = index;" [formGroup]="checkRuleArrForm.get(i.toString())" [@slideDown]>
        	<mat-form-field>
          		<mat-select placeholder="参数数据源" formControlName="dataSource">
            		<mat-option *ngFor="let source of sourceArr" [value]="source.value">
              			{{source.viewValue}}
            		mat-option>
          		mat-select>
        	mat-form-field>
        	<mat-form-field>
          		<input matInput placeholder="关键词" formControlName="keyword">
       		mat-form-field>
        	<mat-form-field>
          		<input matInput placeholder="填写正则匹配" formControlName="regx">
        	mat-form-field>
      	li>
    ul>
    
    <mat-checkbox color="primary" formControlName="weightCtr" (ngModelChange)="getWeightVal($event)">权重控制mat-checkbox>
form>
复制代码

注意事项

  1. 对动态生成的表单进行 *ngFor 需要将伪数组转换为真数组进行操作

  2. 动态生成表单部分的 formGroup 需要通过 checkRuleArrForm.get(i.toString()) 方式进行获取

    • checkRuleArrForm 动态生成的表单, controls 的键为索引
    • get 方法参数必须为 string 类型, 需要进行类型转换
  3. 大部分情况下需要对 FormGroup 进行监听, 判断值是否发生变化

    • 表单中每一项变化都会触发 valueChanges 方法

      formValueChange(form: FormGroup) {
          form.valueChanges.subscribe(res => {
            this.getRequestInfo.emit(this.requestInfoForm);
          });
      }
      复制代码

以上内容仅仅作为记录[方便自己copy代码, 哈哈哈], 对源码未深究, 之后考虑深入了解下~

转载于:https://juejin.im/post/5c9b32056fb9a070ac66b5c5

你可能感兴趣的:(angular7 FormGroup基本使用)