How can I shape the object generated by Frombuilder?

Asked

Viewed 102 times

2

I use Formbuilder to generate an object and send it to an API, but the generated object is not quite the format the API expects. I need to know how to add objects inside objects using Formbuild. I did a "gambiarra" to be able to work, but I wanted to know how to do it more professionally.

createForm(create) {
this.formRegister = this.formBuilder.group({
  nome: [create.nome, [ Validators.required ]],
  email: [create.email, [ Validators.required, Validators.email ]],
  celular: [create.celular, [ Validators.required ]],
  cpf: [create.cpf, [ Validators.required ]],
  senha: [create.senha, [ Validators.required ]],
  sexo: [create.sexo, [ Validators.required ]],
  dataNascimento: [create.dataNascimento, [ Validators.required ]]
});

}

I was using this function to shape my object

objTransf() {
let data = new PreCadastro;
data = {
  'pessoa': {
    'nome': this.formRegister.value.nome,
    'email': this.formRegister.value.email,
    'cpf': this.formRegister.value.cpf,
    'sexo': this.formRegister.value.sexo,
    'dataNascimento': this.formRegister.value.dataNascimento,
    'contato': {
      'celular': this.formRegister.value.celular
    }
  },
  'usuario': {
    'login': this.formRegister.value.email,
    'senha': this.formRegister.value.senha
  },
  'preCadastro': true
  };
  this.addElement(data);
  }

If you have a link to a subject or example, it would be helpful.

1 answer

2


The best would be for every chained object you have. You create another formGroup inside your formGroup so it gets the structure the way you need it.

this.formRegister = this.formBuilder.group({
  pessoa: this.formBuilder.group({
      nome: [create.nome, [ Validators.required ]],
      email: [create.email, [ Validators.required, Validators.email ]],
      celular: [create.celular, [ Validators.required ]],
      cpf: [create.cpf, [ Validators.required ]],
      senha: [create.senha, [ Validators.required ]],
      sexo: [create.sexo, [ Validators.required ]],
 })
 usuario: this.formBuilder.group({
      senha: [create.senha, [ Validators.required ]],
      login: [create.email, [ Validators.required, Validators.email ]]
 })
});

ai use in html like this:

<div formGroupName="pessoa">

Browser other questions tagged

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