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

2mbi3lxu  于 2023-03-16  发布在  Angular
关注(0)|答案(1)|浏览(143)

问题是当我想要更改值时,它总是向我显示第一个选项。
这是我的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);
    });

谢谢!

fivyi3re

fivyi3re1#

您可以使用[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>

相关问题