Angular 4 Select不要在ngModel更改时更新 [英] Angular 4 Select don't update on ngModel change
问题描述
我试图确保在选择新值之后,我调用eventChange()函数并将所选值恢复为默认值.但是会发生什么:ngModel值更新,但是所选值保持不变.我应该如何将所选值和ngModel值设置为相同?
I am trying to make that after new value is selected, I call eventChange() function and restore selected value to default. But what happens: ngModel value updates, but selected value stays the same. How should I do that selected value and ngModel value would be the same?
HTML文件
<select [(ngModel)]="selectedValue"
(change)="eventChange()"
>
<option [disabled]="true"
[ngValue]="-1">
Choose an option
</option>
<option *ngFor="let item of myList index as i"
[ngValue]="i"
>
{{item.name}}
</option>
</select>
组件文件中的功能
selectedValue = -1; //works //Option in select is changed
eventChange(){
this.selectedValue= -1; //don't work
//Function is called,
//Value changes
//But selected Option in Select doesn't change
}
评论: 在运行的网页上(刷新),正确设置了select的第一个值,如果我在组件文件中将变量 selectedValue 设置为其他索引,则选择了另一个值,但它仅在运行时起作用,而在功能上不起作用)
Comment: On running web page(refresh) first value of select is set properly, if in component file I set variable selectedValue to other index the other value is selected, but it works only on run, but not in function)
我也发现了这个问题 Angularjs:选择何时不更新ng-model已更新 但这是对AngularJS使用ng-options而不是ng-repeat的答案,在角度4中,我只发现* ngFor ...
Also I found this question Angularjs: select not updating when ng-model is updated But here is an answer to AngularJS for using ng-options, instead of ng-repeat, in angular 4 I found only *ngFor...
更新: 澄清以防万一:正在调用函数,但是我想通过javascript更改所选的选项.我通过更改ngModel值来尝试此操作,但是即使更改ngModel值,所选选项也不会更改.
Update: Clarification just in case: function is being called, but I want change selected option through javascript. I try this by changing ngModel value, but even when ngModel value is cahnged, selected option doesn't change.
推荐答案
使用 ngModelChange ,您无需 [ngValue]
Use ngModelChange and you don't need [ngValue]
<select [(ngModel)]="selectedValue"
(ngModelChange)="eventChange()"
这篇关于Angular 4 Select不要在ngModel更改时更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!