Search code examples
angularangular-reactive-formspatchvalue

How do I set a value, from an API request, to a formControl in Angular?


I have a service that gets data from a REST API. The return looks like this:

{
 "users": [
  {
    "id": 1,
    "firstname": "John",
    "email": "test@aol.com",
    "lastname": "Smith"
  }
 ]
}

I want to be able to take the email value and set it to my emailID formControl by default:

templateForm = this.fb.group({
  appCode: [''],
  accountType: [''],
  emailId: [''],
  IDV: [''],
  emailSubject: [null,Validators.required],
  emailBlurb: [null,Validators.required],
  envelopeRequest: this.fb.group({
   compositeTemplates: this.fb.array([this.newCompositeTemplate()]),
  }),
});

I've added the service inside of ngOnInit along with a patchValue method but the form control isn't populating.

ngOnInit() {
 this.userservice.getUsers().subscribe((res:User) => {
  this.userData =res;
 }); 
 this.templateForm;    
 this.templateForm.patchValue({
  emailId: this.userData.email    
 });
}

I'm not sure why this is happening if I hardcode an email address inside the patchValue it works fine. Thanks for any response to this. I've included a link for reference. Stackblitz


Solution

  • I would do this because you request returns users and not a simple User data.

    ngOnInit() {
    
        this.userservice.getUsers().subscribe((res) => {
     
        this.userData =res.users[ 0 ];
     
        this.templateForm.patchValue({
          emailId: this.userData.email   
        });
    
      }); 
    }
    

    working Stackblitz