且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ngModel中的Angular 2-更改未反映在下拉列表中

更新时间:2023-02-12 10:11:28

我能想到的解决方案是创建先前选择的对象/值的引用,并在ngModelChange触发它时将其与函数一起传递.我不得不进行一些有关如何从组件设置select值的研究.这是我的示例代码:

The solution I could come up with is to create a reference of the previously selected object/value and pass it with the function when ngModelChange triggers it. I had to some research on how to set value for select from component. Here's my example code:

html:

<select #selectBox
            [(ngModel)]="selectedClientVersion" 
            (ngModelChange)="selectedCurrentVersion(prevSelectedClientVersion, selectedClientVersion, selectBox)" 
            (focus)="prevSelectedClientVersion=selectedClientVersion">
        <option *ngFor="let i of clientVersions" 
                [ngValue]="i"> 
          {{ i.value }}
        </option>
 </select>

component.ts:

component.ts:

selectedCurrentVersion(prevObj, currObj, selectbox){

    var r = confirm("Do you really want to change?");
    if (r == true) {
      this.selectedClientVersionObj = currObj;
    }
    else{
      selectbox.selectedIndex = this.clientVersions.indexOf(prevObj);
      this.selectedClientVersionObj = prevObj;
      this.selectedClientVersion = prevObj;
    }

}

柱塞演示

希望这会有所帮助:)