Rafael Augusto
Rafael Augusto

Reputation: 797

get values in Reactive Forms

I'm having trouble populating my entity data on my reactive form.

I can get the data, but I do not know how or when is the best time to fill out my form with these values.

this is my form:

import { Component, OnInit, Input } from '@angular/core';

import { FormArray, FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';

import { Empresa } from '../empresa.model';

import { HttpClient } from '@angular/common/http';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-empresa-detalhe',
  templateUrl: './empresa-detalhe.component.html',
  styleUrls: ['./empresa-detalhe.component.scss']
})
export class EmpresaDetalheComponent implements OnInit {

  empresaForm: FormGroup;

  nomeControl: FormControl;
  statusControl: FormControl;

  empresa: Empresa = {};

  constructor(private route: ActivatedRoute, private http: HttpClient, private fb: FormBuilder) {}

  ngOnInit() {
    this.getEmpresa(this.route.snapshot.params['nome']);
    this.createForm();
  }

  createForm() {
    this.nomeControl = new FormControl('', [
      Validators.required,
      Validators.minLength(3),
      Validators.maxLength(10)
    ]);
    this.statusControl = new FormControl('', [
      Validators.required,
      Validators.minLength(3),
      Validators.maxLength(10)
    ]);

    this.empresaForm = this.fb.group({
      nome: this.nomeControl,
      status: this.statusControl
    });
  }

  onSubmit() {
    const empresa = this.empresaForm.value as Empresa;
    console.log('Empresa: ', empresa);
  }

  getEmpresa(nome) {
    this.http.get('http://localhost:8080/app-rest/api/empresasAereas/nome/' + nome).subscribe(data => {
      this.empresa = data;
      console.log(this.empresa); // this return my data with values
    });
  }

}

my getEmpresa return my empresa model, What is the best way to fill my form data with my entity data?

Upvotes: 1

Views: 12582

Answers (3)

M Usman Nadeem
M Usman Nadeem

Reputation: 425

if you console complete object of reactive form. you find a key with name "value".

console.log(this.empresaForm.value)

contain all FormControls values,

Upvotes: 0

Ashish Ranjan
Ashish Ranjan

Reputation: 12960

The first thing you should do in you ngOnInit() is to build the form and then call the getEmpresa() function. (you are doing the reverse).

ngOnInit() {
    this.createForm();
    this.getEmpresa(this.route.snapshot.params['nome']);
}

and then set the form data in your getEmpresea() function, Ideally this should be the place you set the data to the form, but anyway that will depend on how you want to do the implementation.

If the data returned by your getEmpresa() function has the same structure as that of the form, then you can simply do:

this.http.get('http://localhost:8080/app-rest/api/empresasAereas/nome/' + nome).subscribe(data => {
  ...
  this.empresaForm.setValue(data);
  ...
});

If your form has a different structure, then do something like inside the subscription:

this.empresaForm.setValue({
   nome:    data.nomeValue,
   status: data.statusValue
});

Here for setting values to the form model you have options like: setValue() and patchValue(). @Tomasz Kula has clearly stated the difference, You can also See: this link from angular.

Upvotes: 2

Tomasz Kula
Tomasz Kula

Reputation: 16847

You should update your form after the http get call returns. You can use patchValue or setValue methods.

patchValue()

Patches the value of the FormGroup. It accepts an object with control names as keys, and will do its best to match the values to the correct controls in the group.

setValue()

Sets the value of the FormGroup. It accepts an object that matches the structure of the group, with control names as keys.

This method performs strict checks, so it will throw an error if you try to set the value of a control that doesn't exist or if you exclude the value of a control.

It accepts both super-sets and sub-sets of the group without throwing an error.

getEmpresa(nome) {
  this.http.get('http://localhost:8080/app-rest/api/empresasAereas/nome/' + nome).subscribe(data => {
    empresaForm.setValue(data)
  });
}

Also, your createForm() method can be simplified like this:

createForm() {
  this.empresaForm = this.fb.group({
    nomeControl: ['', [
      Validators.required,
      Validators.minLength(3),
      Validators.maxLength(10)
    ]],
    statusControl: ['', [
      Validators.required,
      Validators.minLength(3),
      Validators.maxLength(10)
    ]],
  })
}

Upvotes: 3

Related Questions