How can I setvalue a select options in Angular 7?

1

This is my html:

 <div class="col-lg-4 col-md-4 col-sm-12 mt-4">
                    <div class="form-group">
                        <select class="form-control" id="operator-groups" formControlName="operators">
                            <option disabled selected value>Seleccione</option>
                            <option *ngFor="let operator of operators; let i = index;">{{operator.desc}}</option>
                        </select>
                    </div>
                </div>

This is my component:

this._operatorgroups.index().subscribe(res => {
      let operators = <OperatorGroups[]>res;
      this.operators  = operators;
      this.registerForm.controls['operators'].setValue(res[1].desc);
    });

Thank you!

    
asked by David 26.11.2018 в 15:36
source

1 answer

1

The way to work with select is using ngValue:

<div class="col-lg-4 col-md-4 col-sm-12 mt-4">
    <div class="form-group">
        <select class="form-control" id="operator-groups" formControlName="operators">
            <option disabled selected value>Seleccione</option>
            <option *ngFor="let operator of operators" [ngValue]="operator">{{operator.desc}}</option>
        </select>
    </div>
</div>

In this way, the value in the form control does not use any operator attribute, it uses the whole operator object, which can be very convenient:

this._operatorgroups.index().subscribe((operators :OperatorGroups[]) => {

  this.operators  = operators;
  this.registerForm.controls['operators'].setValue(operators[1]);
});
    
answered by 26.11.2018 в 17:06