在Angular中动态地向FormGroup添加控件

145

如何在Angular中动态添加FormControl到FormGroup?

例如,我想添加一个名称为“new”的必填控件,其默认值为''。


这也可能有所帮助: https://dev59.com/clMI5IYBdhLWcg3wyurE - user3025289
就像Siro回答了你的问题一样,你可以使用addControl方法向表单组添加新的输入。我有一个小项目研究动态表单。希望对你有用。https://stackblitz.com/edit/angular-eypxbq?embed=1&file=src/app/app.component.html - Michael Charles
7个回答

293

addControl 是你所需要的。请注意第二个参数必须是一个像这样的 FormControl 实例:

this.testForm.addControl('new', new FormControl('', Validators.required));

如果需要,您还可以使用setValidators方法动态添加验证器。调用此方法会覆盖任何现有的同步验证器。


抱歉,请问如何添加多个验证器,例如: this.testForm.addControl('new', new FormControl('', [Validators.required, Validators.max(100)]); - Miguel Navas
运行得非常顺畅。 - Ali Celebi
对我来说,为了使其在Angular 14中起作用,我需要将formGroup: FormGroup添加到类型中。 - user11006286
请注意,您可以使用数组添加多个验证器: this.testForm.addControl('name', new FormControl('', [Validators.required, Validators.max(5)])) - A.Casanova

66
如果您正在使用FormBuilder创建表单,您也可以使用它来添加控件:
constructor(private fb: FormBuilder) { }
    
method() {
  this.testForm.addControl('new', this.fb.control('', Validators.required));
}

1
如何在值更改订阅中添加控件时停止事件发射? - Sreenath

10

简单使用:

  this.testForm.addControl('new', this.fb.group({
      name: ['', Validators.required]
    }));

5

Angular 14为表单添加了类型。以下是新语法的样子:

表单声明

public form = new FormGroup<{ new?: FormControl<string | null> }>();

请注意,new 控件必须声明为可选项。如果未首先声明该字段,则无法使用 addControl
对于较大的表单,您可以使用接口:
interface MyForm {
    field1: FormControl<string | null>;
    field2: FormControl<string | null>;
    new?: FormControl<string | null>;
}

public form = new FormGroup<MyForm>({
    field1: new FormControl<string | null>('', Validators.required),
    field2: new FormControl<string | null>('', Validators.required),
});

在表单中添加控件

this.form.addControl('new', new FormControl<string | null>('', Validators.required));

3
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
  selector: 'app-component-name',
  templateUrl: './component-name.component.html',
  styleUrls: ['./component-name.component.scss']
})
export class ComponentName implements OnInit {

    formGroup: FormGroup;        
    constructor(private formBuilder: FormBuilder) {}

    ngOnInit() {
       this.formGroup = this.formBuilder.group({
        firstName: new FormControl('', Validators.required),
        lastName:  new FormControl('', Validators.required),
      });    
    }
    
    // Add single or multiple controls here
    addNewControls(): void {
      this.formGroup = this.formBuilder.group({
         ...this.formGroup.controls,
         email: ['', Validators.required],
         phone: ['', Validators.required]
      });
    }
}

2

我在 Angular 12 中遇到了同样的问题。以下代码片段对我完美地起作用。

声明表单:

public form: FormGroup;

为表单创建一个新的控件:

this.form.addControl('new', new FormControl('', Validators.required));

2
这个答案对我有用,因为Angular 14现在要求表单组需要类型。 - user11006286

1

要动态地向现有的FormArray实例中添加一个新的FormControl,可以使用强制转换技术。

form: FormGroup;

constructor(private fb: FormBuilder){
  this.form = this.fb.group({
    formArrayName: this.fb.array([])
  });
} //

addNewFormArrayInstance(insertIndex: number){
  // insertIndex to insert at a specific position
  const NEWFORMGROUP = new FormGroup({
    'control1': new FormControl(''),
    'control2': new FormControl({value: [], disabled: true}),
    'control3': new FormControl('', Validators.required),
    'control4': new FormControl(true)
  });

  // use push(NEWFORMGROUP) if needed
  (<FormArray>this.form.get('formArrayName')).insert(insertIndex, NEWFORMGROUP);
} //

addControlToFormArrayInstance(index: number){
  // index is the FormArray instance's index to which a new control is to be added
  (<FormGroup>
    (<FormArray>this.form.get('formArrayName')).controls[index]
  ).addControls(
    'newControl', new FormControl('new')
  );
} //

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接