如何在Angular 7中设置选择选项的值?

时间:2018-11-26 16:08:15

标签: javascript html angular angular7

问题是当我想更改值时,它总是向我显示第一个选项。

这是我的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._operatorgroups.index().subscribe(res => {
      let operators = <OperatorGroups[]>res;
      this.operators  = operators;
      this.registerForm.controls['operators'].setValue(res[1].desc);
    });

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用[selected]="condition that will result true for the option you want default"

例如,如果您想要第一个索引(基于组件中的代码),则需要:

<option *ngFor="let operator of operators; let i = index;" [selected] = "i==1">{{operator.desc}}</option>

另一个示例是,如果您想让说算符desc'xyz'被选中,您会喜欢:

 <option *ngFor="let operator of operators; let i = index;" [selected] = "operator.desc == xyz">{{operator.desc}}</option>