首页 > 解决方案 > 如何使用反应形式创建动态角度形式?

问题描述

我需要使用角度反应创建一个动态表单。但是这有很多子表单组,这些组可能会根据表单选择框的值而改变。

  profileForm = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl(''),
    department: new FormControl('')
  });

部门类型是'a', 'b', 'c'.

如果用户选择'a',我将添加一个名为"departmentSettings"profileForm的新 FormGroup

aFormGroup =  new FormGroup({
    xWorkTime: new FormControl(''),
    yWorkTime: new FormControl('')
})

profileForm = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl(''),
    department: new FormControl(''),
    departmentSettings: new FormGroup({
        xWorkTime: new FormControl(''),
        yWorkTime: new FormControl('')
    })
});

如果用户选择'b',我将FormGroup在 profileForm 中添加一个新的

bFormGroup =  new FormGroup({
    someProperty: new FormControl(''),
    otherProperty: new FormControl('')
})

profileForm = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl(''),
    department: new FormControl(''),
    departmentSettings:  new FormGroup({
        someProperty: new FormControl(''),
        otherProperty: new FormControl('')
    })
}); 

其他情况是这样的。那么我怎么能用简单的角度来做到这一点呢?

标签: angularangular8angular-reactive-forms

解决方案


在您的 html 中,将 (change)='someFunction()' 属性添加到部门输入。

<input matInput type="select" #departmentInput formControlName="department"
                 (change)="doChange($event)">

当输入的值发生变化时,这将触发该函数,然后您可以将新的表单控件添加到您的反应式表单。

反应式表单有一个 FormGroup.addControl() 方法可以做到这一点。 https://angular.io/api/forms/FormGroup


推荐阅读