简体   繁体   中英

Angular 4 Select don't update on ngModel change

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.

Use ngModelChange and you don't need [ngValue]

<select [(ngModel)]="selectedValue"
       (ngModelChange)="eventChange()"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM