问题
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 file
<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>
Function from Component file
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
}
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)
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...
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.
回答1:
Use ngModelChange and you don't need [ngValue]
<select [(ngModel)]="selectedValue"
(ngModelChange)="eventChange()"
来源:https://stackoverflow.com/questions/48634129/angular-4-select-dont-update-on-ngmodel-change