绑定新项目后选择丢失选择

时间:2016-10-28 05:41:35

标签: angular

我对Angular 2上的select元素有疑问。 我在两个不同版本的Angular2上创建了2个示例但行为相同:

请按照以下步骤操作:从' 2'中选择更改到' 1' - >点击按钮'测试' - >

  • 版本2.0.0-rc.1 - >没关系
  • 版本2.0.2 - >它的失败,选择失败

这些代码揭示了这一点:

@Component({
    selector: 'app',
    template: `
      <select class="form-control" [ngModel]="value">
    <option *ngFor="let item of items" [ngValue]="item.value">
        {{item.text}}
    </option>
</select>
<button type="button" (click)="test()">Test</button>
    `
})
export class App {

  items: any[];
    value: any;

  constructor() {
    this.items = [
            { text: '1', value: 1 },
            { text: '2', value: 2 }
        ];
        this.value = this.items[1].value;
  }

  test() {
    this.value = this.items[0].value;
        this.items = [
            { text: '1', value: 1 },
            { text: '2', value: 2 },
            { text: '3', value: 3 }
        ];

    }

}

我想知道版本2.0.2有错误吗?怎么解决这个问题。感谢。

2 个答案:

答案 0 :(得分:2)

当您点击按钮Test时,您的[ngModel]属性仍然与之前的值相同。 移动

this.value = this.items[0].value;

test()的末尾也无济于事,因为

1 === 1
isPropertyUpdated指令中ngOnChanges内的

和方法NgModel将返回false。

所以我认为你必须改变你在angular2规范中提到的声明

像:

[ngValue]="item"

并在组件中:

constructor() {
  this.items = [
    { text: '1', value: 1 },
    { text: '2', value: 2 }
  ];
  this.value = this.items[1];
}

test() {
  this.items = [
    { text: '1', value: 1 },
    { text: '2', value: 2 },
    { text: '3', value: 3 }
  ];
  this.value = this.items[0];
}

在js {} !== {}

这可以帮助您使用select[ngModel]

来避免奇怪的行为

http://plnkr.co/edit/vdyqnwR6HpqHD8FoqwAA?p=preview

答案 1 :(得分:0)

这是因为您创建了一个新数组。 [ngValue]比较对象标识而不是数据内容。如果它获得了不同的对象实例,则它不会认为它是相同的并且不会将其显示为已选中。

更新value中的test()以反映新选择,或者不创建新数组,而只是修改之前创建的数组。

实际移动

this.value = this.items[0].value;

test()函数的末尾将解决您的问题。

Plunker example