如何以编程方式更改 html select 标记中的 selected 选项

How to programmatically change the selected option in an html select tag

我在 html 到 select 的价格范围内有一个 select 组。用户可以select一个范围,然后根据select离子过滤结果。这工作正常,但是用户也可以从完全不同的地方(搜索框)重置结果。我需要更改实际显示在 select 框中的 selection,以便我可以将其重置为 "show all",这样当用户实际上已经重置了搜索框中的结果。

我可以通过以下方式更改 selected 的实际值:

document.getElementById("selectedPriceRange").setAttribute("value","0")

这确实会更改 select 框中的值,但框本身仍会显示上次 select 编辑的选项。

如何在不实际 select 其他选项的情况下更改 select 框中显示的文本?

这是我的 select 盒子:

<select #priceRangeOptions class="custom-select" id="inputGroupSelect01">
     <option *ngFor="let priceRange of priceRangeOptions; let i=index"
     id="selectedPriceRange" [value]="i">{{priceRange}}</option>
</select>

在select你所要做的就是设置ngModel属性,然后你可以将变量值更改为设置值。

<select #priceRangeOptions [(ngModel)]="selectedValue" class="custom-select" id="inputGroupSelect01">
 <option *ngFor="let priceRange of priceRangeOptions; let i=index"
 id="selectedPriceRange" [value]="i">{{priceRange}}</option>
</select>

selectedValue = 'my selected value.';

或者您可以使用 javascript 来做到这一点

document.getElementById('inputGroupSelect01').value = "value";

不要使用Javascript查询DOM/设置值

此外,根据您发布的内容,您不需要索引(尽管您可能需要)

相反,你 can do this:

<select #priceRangeOptions class="custom-select" id="inputGroupSelect01" [(ngModel)]="option">
     <option *ngFor="let option of options;"
     id="selectedOption" [value]="option">{{option}}</option>
 </select>

<button type="button" (click)="setHotDog()">Choose the hotdog</button>

[()] 语法表示双向绑定。

作为概念证明,此打字稿设置了模型值:

export class AppComponent  {
  name = 'Angular';
  option: string;
  options: string[] = ['One', 'Another Choice','Wow, A Hotdog?'];

  setHotDog(){
    this.option = this.options[2];
  }
}

这就是 Angular 的方法,也是正确的方法