ArthCode
ArthCode

Reputation: 102

How to init default values for Angular Form from async request (form control)

I have settings on my website and I need to fill all the fields with default values - current settings of my user.

After user entering his settings, I make an asynchronous GET request and after it completes, I need to pass his settings as default values to my form fields.

As I know, I can pass default values using this syntax:

this.validateForm = this.fb.group({
    language: ['default_value', [Validators.nullValidator]],
    timeZone: ['default_value', [Validators.nullValidator]],
    firstName: ['default_value', [Validators.nullValidator]],
    lastName: ['default_value', [Validators.nullValidator]],
    gender: ['default_value', [Validators.nullValidator]],
    address: ['default_value', [Validators.nullValidator]]
});

But look, Angular needs me to initialize this form group instantly in constructor, but I can't, as asynchronous request takes some time, until it, fields must be empty.

Moreover, I think, that it is much easier to do this in HTML, for example through using ngModel, but it doesn't work with formControl, or [value] but this is also not a solution, as form control just ignores info, that I passed to [value] attribute and it there's not ability to pass [value] to select, as I use not just regular HTML , but Ng-Zorro and it doesn't have [value] attribute.

Upvotes: 0

Views: 3035

Answers (2)

d1fficult
d1fficult

Reputation: 1083

If you want to update only few values of your form after async request completes. You must use patchValue() instead of setValue().

As setValue() is used to set the all the formcontrols your form got where you can use patchValue() to update only the few controls you want to.

So, to update the complete form go for setValue(), setValue() requires all the controls with respective values else it throws error like this :-

this.validateForm.setValue({
        language: res.language,
        timeZone: res.timeZone,
        firstName: res.firstName,
        lastName: res.lastName,
        gender: res.gender,
        address: res.address
      })

or if updating only few controls pick patchValue() like this :-

this.validateForm.patchValue({
    language: res.language,
    firstName: res.firstName
  })

Upvotes: 4

uiTeam324
uiTeam324

Reputation: 1245

You can set the values of the form again after getting the values from your api call using setValue method.

Sample:

   this.service.functionName().subscribe((res) => {
  this.validateForm.setValue({
    language: res.language,
    firstName: res.firstName
  })
})

Upvotes: 1

Related Questions