assign value to FormControl

0

I have a form where I need to print what I receive from the service in the imput using formControlName.

<form [formGroup]="VendedorForm">
     <input type="text" formControlName="nombres">
     <input type="text" formControlName="apellidos">
     <input type="text" formControlName="identidad">
</form>

This is my service which I assign to a variable, but I need to assign it to SellerForm

this.VendedorForm = this.formBuilder.group({
  nombres: ['', [Validators.required]],
  apellidos: ['', [Validators.required]],
  identidad: ['', [Validators.required]]
});           

getVendedor() {
   this.vendedorService.getVendedor(this.id)
   .subscribe((response) => {
     this.vendedor = response;
   }
}
    
asked by mserradas 14.05.2018 в 19:11
source

1 answer

0

I see that you use a reactive form 'SellerForm' where you will show the information.

The 'getVendedor' function collects the data returned from the service. There are two:

1.- Create the form with the value in the initialized fields.

private getVendedor = (): void => {
    this.vendedorService.getVendedor(this.id).subscribe(
        (response: any) => {
            // aqui cacha el valor del objeto que te interesa, reemplaza 'response.body.data' por el tullo
            this.initForm(response.body.data);
        },
        (error: any) => {
            console.log(error);
        },
        () => {}
     );
}
private initForm = (_data: any): void => {
    this.VendedorForm = this.formBuilder.group({
        nombres: [_data.nombres, [Validators.required]],
        apellidos: [_data.apellidos, [Validators.required]],
        identidad: [_data.identidad, [Validators.required]]
    });
}

2.- Use 'setValue' to assign the value to each field of the form.

private getVendedor = (): void => {
    this.vendedorService.getVendedor(this.id).subscribe(
        (response: any) => {
            // aqui cacha el valor del objeto que te interesa, reemplaza 'response.body.data' por el tullo
            this.VendedorForm.controls['nombres'].setValue(response.body.data.nombres);
            this.VendedorForm.controls['apellidos'].setValue(response.body.data.apellidos);
            this.VendedorForm.controls['identidad'].setValue(response.body.data.identidad);
        },
        (error: any) => {
            console.log(error);
        },
        () => {}
     );
}
    
answered by 18.05.2018 в 03:50