简体   繁体   中英

Patch value to select box in Angular 9

I'm trying to patch value in my edit form using reactive forms. I'm able to console the value, but it's not being binded to my html. If i try the same thing in input box, i'm able to see the value. Can anyone let me know where it's going wrong?

patchGrowLicense(licenseObj) {
    console.log(licenseObj.landId);
    this.httpService.getAllFarmById(licenseObj.landId).subscribe(response => {
      this.farmObj = response;
      console.log(this.farmObj.street + ' , ' + this.farmObj.suburb + ' , ' + this.farmObj.town);
      this.formGrowLicense.patchValue({
        town:this.secondFormLocation.value.propertyName,
        growLicFromLoc: this.farmObj.street + ' , ' + this.farmObj.suburb + ' , ' + this.farmObj.town,
       
      });

    });
  }

  getAllFarmLocations() {

    this.httpService.getAllFarmLocations().subscribe(response => {
      this.locations = response;

      console.log(this.locations);
    });
  }

html

<div class="form-group col-sm-4">
  <label>Farm Location</label>

  <select class="form-control" (change)="changeEvents($event)" formControlName="growLicFromLoc">

    <!-- <option disabled>Select Farming Location</option> -->
    <option>Select Farming Location</option>
    <option *ngFor="let location of locations" [value]=location.premisesId>
      {{location.street+" , "+location.suburb+" , "+location.town}}</option>
  </select>

  <div *ngIf="!formGrowLicense.controls['growLicFromLoc'].valid && (formGrowLicense.controls['growLicFromLoc'].touched || isSubmitted)">
    <div class="invalid-feedback" style="display: block;">Please enter farm location</div>
  </div>
</div>

look here

<option *ngFor="let location of locations" [value]=location.premisesId>

the value of the option is ID. so the model should contain ID, and I believe what you are trying to assign is not Id. I assume the fix would be to update the value you are trying to set

this.formGrowLicense.patchValue({
        town:this.secondFormLocation.value.propertyName,
        growLicFromLoc: this.farmObj.id,
      });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM