Angular 4 Select don't update on ngModel change

时光总嘲笑我的痴心妄想 提交于 2019-12-13 03:34:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!