Map Formgroup to an object

Asked

Viewed 60 times

-1

I would like to know if you have any better way to do the assignment of the values of a formGroup on an object. The bass follows what I did, but I think it’s kind of weird, but I also couldn’t find another way.

get t() {
    return travelersForm.controls;
  }

This is my formGroup

this.t.push(
  this.formBuilder.group({
    docType: [{ value: 'CPF', disabled: true }],
    document: ['', Validators.compose([Validators.required, cValidatorCpf])],
    name: ['', Validators.required],
    dateBirth: ['', Validators.required],
    age: [{ value: nAge, disabled: true }],
    email: ['', [Validators.required, Validators.email]],
    phone: ['', Validators.required],
  }, {
    validator: Validators.compose([
      cValidatorAge('dateBirth', 'age', this.travelerService.currentInsuranceValue),
    ])
  })
);

This is where I’m assigning the values of formGroup to an object to do the post pro back.

    setInsuredObj() {
    let insured: Insured;
    insured.id = 0;
    insured.idUser = this.user.idUser;
    insured.typeSex = {id: 1, initials: 'M', description: 'Masculino', code: '1'} as TypeSex;
    insured.document = this.t.controls[0]['controls'].document;
    insured.name = this.t.controls[0]['controls'].name.value;
    insured.birthdate = this.t.controls[0]['controls'].dateBirth.value;
    insured.email = this.t.controls[0]['controls'].email.value;
    insured.zipCode = this.af.zipCode.value;
    insured.address = this.af.address.value;
    insured.number = this.af.number.value;
    insured.complement = this.af.complement.value;
    insured.neighborhood = this.af.neighborhood.value;
    insured.state = this.af.state.value;
    insured.city = this.af.city.value;
    insured.telephone1 = this.t.controls[0]['controls'].phone.value;
  }

I wonder if there is a better way to do this because I have a formArray that would be kind of boring to do so "at hand" too.

1 answer

1


One of the means is to use destructuring and assemble your object

const insured = { this.user.userId, typeSex: {id: 1, initials: 'M', description: 'Masculino', code: '1'} as TypeSex, ... }

you could assign this to a method that returns you the "mapped object"

mapearObjetos(): Insured {
  for (let item of this.t) {
     transformObjeto(item); // metodo que retorna objeto usando 
     // desestruturação(Destructuring)
  }
}

if you have multiple items, you will have to save on a list, have other means of doing, follow the reference to use unstructuring.

destructuring

  • Got it. Thanks for the help I’ll take a look at this

Browser other questions tagged

You are not signed in. Login or sign up in order to post.