Angular 如何以编程方式更改下拉列表值
我有一个下拉菜单,我想在单击按钮时更改组件文件中的下拉值Angular 如何以编程方式更改下拉列表值,angular,typescript,angular8,Angular,Typescript,Angular8,我有一个下拉菜单,我想在单击按钮时更改组件文件中的下拉值 <select id="currentPeriodDropDown" (change)="onCurrentSnapshotPeriodChange()" [(ngModel)]="currentSnapshotPeriod" class="form-control form-control-sm mr-1 form-control-sm-ipad" > &
<select
id="currentPeriodDropDown"
(change)="onCurrentSnapshotPeriodChange()"
[(ngModel)]="currentSnapshotPeriod"
class="form-control form-control-sm mr-1 form-control-sm-ipad"
>
<option [ngValue]="period" *ngFor="let period of snapshotPeriods"
>{{ period?.periodName }}
</option>
</select>
{{period?.periodName}}
我想更改组件文件中的值,而无需从下拉列表中选择选项。请尝试以下代码
this.currentSnapshotPeriod = "some value"; /* This value should exist in option values*/
您需要另一个变量,然后将其设置为空。 如果不为空,则select中的显示为该变量,如果为空,则显示另一个变量。例如: TS文件:
var displayInSelect: string;
buttonClicked() {
this.displayInSelect = 'Whatever You Want';
}
然后您的HTML是:
<select id="currentPeriodDropDown"
(change)="onCurrentSnapshotPeriodChange()"
[(ngModel)]="currentSnapshotPeriod"
class="form-control form-control-sm mr-1 form-control-sm-ipad">
<option [ngValue]="period" *ngFor="let period of snapshotPeriods">
{{ displayInSelect?displayInSelect:(period?.periodName) }}
</option>
</select>
{{displayInSelect?displayInSelect:(句点?.periodName)}
然后按钮(单击)将调用函数“buttonClicked”
请注意,这不会更改您选择的选项,只有select中显示的值您是否尝试设置currentSnapshotPeriod?请出示您的ts代码。@Giannis是的,这不起作用。因此,基本上当前选定的项目将被替换。所以对于ex,如果我们有a,b,c,d,当前选择的项目是b,然后我选择c,然后我执行这个代码,我得到的下拉值是a,b,b,我不确定预期的结果是什么。请检查并提供一个演示,如果你喜欢。我尝试了这个,但它只是改变了下拉列表的值,因此将有2个项目。因此,基本上当前选定的项目将被替换。对于ex,如果我们有a,b,c,d,当前选择的项目是b,然后我选择c,然后我执行这个代码,我得到的下拉值是a,b,b,d