Vipin
Vipin

Reputation: 938

Angular 6 default value of select is not getting selected in Reactive Form

I have a form which is shown below. And having a zone drop down with default value is "ALL" and other values are populated from an api call.

 <form method="POST" for enctype="multipart/form-data" [formGroup]="unitSearchForm">
            <div class="form-group">
              <label for="Zone">Zone</label>
              <select class="form-control" id="zone" formControlName="zoneId">
                <option [ngValue]="0">All</option>
                <option [ngValue]="zone.ZoneId" *ngFor="let zone of (_zones|async)?.Result">{{ zone.ZoneName}}</option>
              </select>
            </div>
            <div class="form-group">
              <input class="form-control" type="text" id="search" formControlName="unitName"
                placeholder="Search by Unit Name" />
            </div>
            <div class="form-group">
              <select class="form-control" formControlName="status">
                <option [ngValue]="status.Code" *ngFor="let status of _statusArr">{{status.Name}}</option>
              </select>
            </div>
            <div class="align-self-end form-group">
              <button type="submit" class="btn  btn-primary" (click)="SearchUnits()"><i
                  class="fa fa-fw fa-search"></i>Search</button>
            </div>
          </form>

/*
Component Code
*/

      ngOnInit() {
        this.InitilizeSearchForm();
        this.InitilizeSelectors();
      }


      private InitilizeSearchForm() {
        this.unitSearchForm = this._fb.group({
          zoneId: ['0'],
          unitName:['',Validators.maxLength(100)],
          status:['A']
        });
      }

      private InitilizeSelectors(){
        let searchCriteria: IDictionary = {}
        this._statusArr=this._dataservice.GetStatus();
        this._zones = this._adminService.Getzones(searchCriteria);
        searchCriteria["status"] =  this.unitSaveForm.get('status').value;
      }

How do i select the "All" in the zone drop down? I tried to set the value when I was initialising the form. But it is not working. Always the first selected value is nothing.

Upvotes: 4

Views: 6060

Answers (1)

Vadim
Vadim

Reputation: 3439

You can use [value] binding for options and [selected] binding for All option:

<div class="form-group">
  <label for="Zone">Zone</label>
  <select class="form-control" id="zone" formControlName="zoneId">
    <option value="All" [selected]="'All'">All</option>
    <option [value]="zone.ZoneId" *ngFor="let zone of (_zones|async)?.Result">{{ zone.ZoneName}}
    </option>
  </select>
</div>

Check stackblitz

Upvotes: 2

Related Questions