Home > Software design >  Angular FormGroup array
Angular FormGroup array

Time:01-31

I have a problem with the set the data to the form array. Scenario is when filling user details, some users have multiple addresses.

here is User.ts

export interface User {
  id?: number;
  name: string;
  age: number;
  address: MyAddress;
}

MyAddress.ts

export interface MyAddress {
  id?: number;
  line1: string;
  line2: string;
  postalCode: string;
  city: string;
}

In component.ts file

myForm = this.formBuilder.group({
    name: ['', Validators.required],
    age: ['', Validators.required]
});

myFormAddress = this.formBuilder.group({
    address: this.formBuilder.array([]),
});

setDetail(): User {
    let myObj = new User();
    myObj.name = this.myForm.controls.name.getRawValue();
    myObj.age = this.myForm.controls.description.getRawValue();
    
    myObj.address = {
      //need to set form array dta here
    }
    
    return myObj;
  }

CodePudding user response:

You needn't two formGroups:

myForm = this.formBuilder.group({
    name: ['', Validators.required],
    age: ['', Validators.required],
    address: this.formBuilder.array([]),
});

CodePudding user response:

Your User interface should reflect the possibility of having multiple addresses:

export interface User {
  id?: number;
  name: string;
  age: number;
  address: MyAddress[];
}

and address should be a part of myForm:

myForm = this.formBuilder.group({
  name: ['', Validators.required],
  age: ['', Validators.required],
  address: this.formBuilder.array([]),
});

Then you should be able to get the array like you do with a regular form control:

myObj.address = this.myForm.controls.address.getRawValue();

Another option is to just get the whole object from the form value:

myObj = this.myForm.value as User;
  • Related