How can I show the clientName in the formbuilder?

0
export class UpdateUserComponent {

   registerForm: FormGroup;
   public users:Array<User> = [];
   public clientName: string;
   public password: string;

   constructor(
       private formBuilder: FormBuilder,
       private _userService:UserService,
   ) {}

  ngOnInit(){
    this._userService.edit(0).subscribe(res => {
      let users = <User[]>res;
      this.clientName = res.clientName;
      console.log(this.clientName);
  });

  this.registerForm.controls['clientName'].setValue(this.clientName);

    this.registerForm = this.formBuilder.group({
      'clientName': [this.clientName],
      'email': [''],
      'phone': [''],
      'password': ['']
    });
  }
}

I get that it is undefined the this.clientName of formBuilder .

How can I do it?

Thank you!

    
asked by David 22.11.2018 в 17:19
source

2 answers

0

You do not sample if you have declared this.clientName, but since you have commented that you are using formBuilder, I understand that you do not.

To assign a value to a formBuilder field, you have to do it in the following way:

this.registerForm .controls['nombreCampo'].setValue("ValorCampo");

This is the code you have to have:

this.registerForm = this.formBuilder.group({
  'clientName': [this.clientName],
  'email': [''],
  'phone': [''],
  'password': ['']
});

this._userService.edit(0).subscribe(res => {
  let users = <User[]>res;
  this.registerForm .controls['clientName'].setValue(res.clientName);
});

Greetings.

    
answered by 22.11.2018 / 17:38
source
0

You must assign it to the controls of your FormGroup

this.registerForm.controls['clientName'].setValue(res.clientName);

Also when you create the FormGroup you should do it like this:

this.formBuilder.group({
    clientName: new FormControl(''),
    email: new FormControl(''),
    phone: new FormControl(''),
    password: new FormControl('')
});

I also suggest changing the creation of your FormGroup in ngOnInit

ngOnInit(){

    this.registerForm = this.formBuilder.group({
        clientName: new FormControl(''),
        email: new FormControl(''),
        phone: new FormControl(''),
        password: new FormControl('')
    });
}
    
answered by 22.11.2018 в 17:55