Issue
Is it possible to pass a variable that comes via API into the formbuilder group so it is included in the POST to my server? Here is what I have so far:
formAPICode: any;
ngOnInit() {
this.ionicForm = this.formBuilder.group({
apiKey: [this.formAPICode], // This is where the API Key should be appearing but doesnt. Console log returns NULL
name: ['', [Validators.required, Validators.minLength(2)]],
email: [
'',
[
Validators.required,
Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,3}$'),
],
],
mobile: ['', [Validators.required, Validators.pattern('^[0-9]+$')]],
street: ['', [Validators.required, Validators.minLength(2)]],
unit: [],
city: ['', [Validators.required, Validators.minLength(2)]],
state: ['', [Validators.required, Validators.minLength(2)]],
zip: ['', [Validators.required, Validators.minLength(5)]],
summary: ['', [Validators.required, Validators.minLength(2)]],
dateTime: [],
existingCustomer: [],
customerConsent: [Validators.required],
});
// Loads WP Company Data
this.wpService.postCompInfoDetails().subscribe((data) => {
this.companyDetail = data;
this.formAPICode = this.companyDetail.acf.forms_api_key;
console.log(this.formAPICode); // returns 45678451-1124d-45ae-bf15-ABC
});
}
Here is the console JSON
form data {"apiKey":null,"name":"John Doe","email":"[email protected]","mobile":"1324567894","street":"1234 Main St","unit":"Suite 202","city":"New York","state":"NY","zip":"10001","summary":"Description of summary","dateTime":null,"existingCustomer":null}
if i change formAPICode to this it works fine. When I introduce the API Key via external API it doesn't
formAPICode = '45678451-1124d-45ae-bf15-ABC';
Solution
It seems like you're assigning formAPICode
value to your form control before it gets any value. Then, when you actually get the value from the API, you're updating the formAPICode
property but the form control already got the initial value.
Try this:
ngOnInit() {
this.ionicForm = this.formBuilder.group({
apiKey: [], // You could leave this blank since we haven't gotten data from API. We will insert it later
// ...your other inputs as normally...
});
// Loads WP Company Data
this.wpService.postCompInfoDetails().subscribe((data) => {
this.companyDetail = data;
this.formAPICode = this.companyDetail.acf.forms_api_key;
// Now that we actually have the value from the API, we can patch that into the form like this
this.ionicForm.patchValue({ apiKey: this.formAPICode });
console.log(this.ionicForm.value) // Should print the entire form value with the actual apiKey that we got recently
});
Answered By - Daniel Guzman
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.