Dynamically add all Formbuilder fields. Angular Front-end

Asked

Viewed 38 times

-2

i have 5 formBuilder fields. 5 are filled with data coming from the database. but this data can be changed by the user

formNum: Formgroup;

recebeDados(){
   this.serviceEndpoint.pegarValores().subscribe(res=> {
       this.formulario(res.data);
  });
}

formulario(result: Dados){
    this.formNum = this.fb.group({
      campo1: result.dado1,
      campo2: result.dado2, 
      campo2: result.dado3,
      campo2 :result.dado4,    
      campo2: result.dado5
    });
}

need to dynamically form this form Builder. for example, these inputs have their initial values:

input1 => 0.3
input1 => 0.7
input1 => 5
total=> 6

but the user went and changed a field:

input1 => 1
input1 => 0.7
input1 => 5

and the total needs to change together: total=> 6.7

any idea?

1 answer

-2


Beauty is until very simple, I will try to pass an explanation more or less to arrive at the final result...

You can start by making a map reduce in Formbuilder values, let’s improve this explanation:

The Formbuilder class has a property that provides access to the Formgroup class, class that has an array with the Formcontrols and their respective values.

It seems confusing but the Formbuilder is organized like this, within it we own the Formgroup that is responsible for grouping the Formcontrols. The Formcontrols class is the representation of a form field, because in it we can get information about the field.

Then adding to what I said earlier, add an eventListerner in the fields of this form for example the listerner onChange.

Every time onChange is fired, map reduce to get the total of all form fields.

After you get the total, use Formgroup to find Formcontrol for the total field.

By the Formcontrol class it is possible to set the field value, so just set the total value.

Of course if the total field is also part of Formgroup at map reduce time, you will need to ignore it gives account.


If you have any questions about what Map Reduce is about, take a look at the stackoverflow itself, you’ll learn that Map Reduce has to do with functional programming.

Browser other questions tagged

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