1

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") });
  }
5
  • 1
    replace [ngValue]="state" with [value]="state.category" in your html <select> tag. ngValue is not required Commented Mar 12, 2019 at 16:43
  • Submit as answer and I can accept, that worked fine. Commented Mar 12, 2019 at 16:47
  • But that has also taken out the default value? Commented Mar 12, 2019 at 16:50
  • What is the default value ? Do you have any already pre selected value? Commented Mar 12, 2019 at 18:49
  • ngValue is used to assign object as well instead of string.If you want to show a preselected value use [(ngModel)]="selectedValue" and set this.selectedValue = <your default value> in the ts file. Commented Mar 12, 2019 at 18:53

1 Answer 1

1

try this :

<select  [(ngModel)]="model.selectedState">
                    <option selected value></option>
                    <option *ngFor="let p of project.favoriteProjects" [value]="state">  {{ state.category }}</option>
                  </select>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.