简体   繁体   English

Angular 4 Select不要在ngModel更改时更新

[英]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. 我试图使它在选择新值之后,调用eventChange()函数并将所选值恢复为默认值。 But what happens: ngModel value updates, but selected value stays the same. 但是会发生什么:ngModel值更新,但是所选值保持不变。 How should I do that selected value and ngModel value would be the same? 我应该如何将所选值和ngModel值设置为相同?

HTML file 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>

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) 注释:在运行的网页上(刷新),正确设置了select的第一个值,如果在组件文件中我将变量selectedValue设置为其他索引,则选择了另一个值,但它仅在运行时起作用,而在功能上不起作用)

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... 我也发现了这个问题Angularjs:当ng-model更新时选择不更新但是这是在Angular 4中使用ng-options而不是ng-repeat的AngularJS的答案,我只发现* ngFor ...

Update: Clarification just in case: function is being called, but I want change selected option through javascript. 更新:澄清以防万一:函数被调用,但是我想通过javascript更改选定的选项。 I try this by changing ngModel value, but even when ngModel value is cahnged, selected option doesn't change. 我通过更改ngModel值来尝试此操作,但是即使更改ngModel值,所选选项也不会更改。

Use ngModelChange and you don't need [ngValue] 使用ngModelChange ,您不需要[ngValue]

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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