I have a form with a select option, those options are brought in via an Array. When I post my form i get an error because I need the post response as json as going to api, and the value gets sent wrong:
currently going as:
category: {category: "Add"}
but needs to go as:
category: "Add"
my form field is:
<label class="form-label" for="category">Category: <sub class="text-secondary">*</sub></label>
</div>
<div class="col-4 col-sm-12">
<select formControlName="category" class="form-select">
<option *ngFor="let state of category" [ngValue]="state">
{{ state.category }}
</option>
</select>
submit function in ts file.
onSubmit() {
if(this.serviceForm.invalid) {
this.serviceForm.setErrors({ ...this.serviceForm.errors, 'required': true });
return;
}
//this.loading = true;
this.uploading = true;
this.service.postRequest(this.serviceForm.value).subscribe((response: any) => {
console.log(response);//On success response
this.router.navigate(['/confirmation'],{queryParams: {value: response.result[0].display_value}});
}, (errorResponse: any) => {
console.log(errorResponse); //On unsuccessful response
});
}
}
service.ts
postRequest(payload) {
//add return//
return this.http.post(this.ApiUrl, payload, { headers: new HttpHeaders().set("Content-Type", "application/json") });
}
[ngValue]="state"with[value]="state.category"in your html<select>tag.ngValueis not requiredngValueis used to assign object as well instead of string.If you want to show a preselected value use[(ngModel)]="selectedValue"and setthis.selectedValue = <your default value>in the ts file.