Home > Blockchain >  Set Formarray data to an object angular
Set Formarray data to an object angular

Time:02-01

I'm a beginner to the angular. need to save multiple addresses to a user. I need to assign address values to an object.
these are interfaces

export interface User {
 name: string;
 myAddress: MyAddress[]
}

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

component.ts file

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

get myAddresses() {
  return this.formAddress.controls['address'] as FormArray;
}

addAddressFormGroup() {
    const addressData = this.formBuilder.group({
      line1: ['', Validators.required],
      line2: [''],
      postalCode: ['', Validators.required],
      city: ['', Validators.required],
    });
    this.myAddresses.push(addressData);
 }

data are set to the obj.

setDetail(): User {
    let myObj = new User();
    myObj.name = this.myForm.controls.name.getRawValue();//this is how i set other values

    myObj.address = {
      // i need to call address arraydata (line1,line2,city,postalcode) here
    }
    
    return myObj;
  }

need to return data as myobj. I can't understand how to do this. is this possible to do?

CodePudding user response:

  1. User is an interface, you can't create User instance with empty constructor unless you declare User as class.

  2. To get the address' value, use this.myAddresses.getRawValue() and cast it as MyAddress[].

Your code should be as below:

let myObj: User = {
  name: this.myForm.controls.name.getRawValue(),
  myAddress: this.myAddresses.getRawValue() as MyAddress[],
};

Demo @ StackBlitz

  • Related