Search code examples
angularangular-forms

Angular: How to append multiple form controls to form group


I am using the latest version of Angular (v6.0.5).

I have a FormGroup consisting of 3 common controls and based on some logic i want to add other multiple controls to the same FormGroup.

I know i can use this.form.addControl() but i dont want to do this for each individual form control

Is there an easy way to do this?

Example:

this.form = this.formBuilder.group({
    'id': new FormControl('', Validators.required),
    'firstName' new FormControl('', Validators.required),
    'lastName' new FormControl('', Validators.required)
});

if (blah) {
    // Append more FormControls here to same FormGroup
    this.form.addControl('houseNumber', new FormControl(''));
    this.form.addControl('street', new FormControl(''));
    this.form.addControl('postCode', new FormControl(''));
}

Solution

  • If you don't want to delay the form creation you can simply do something like that:

    // You can write this sugar, you don't have to write new FormControl
    const form = {
        id: ['', Validators.required],
        firstName: ['', Validators.required],
        lastName: ['', Validators.required]
    };
    
    if (blah) {
        form.someField: ['', Validators.required];
    } else {
        form.someotherField: ['', Validators.required];
    }
    
    this.form = this.formBuilder.group(form);
    

    Or this shorter inline version:

    this.form = this.formBuilder.group({
        id: ['', Validators.required],
        firstName: ['', Validators.required],
        lastName: ['', Validators.required],
        ...(blah ? {form.someField: ['', Validators.required]} : {form.someotherField: ['', Validators.required]})
    });