当ngValue是对象时,Angular 5中选择ngModel的双向数据绑定

问题描述 投票:1回答:1

我使用[(ngModel)]作为整个对象。当我从头开始做这个时工作正常,但是当我在编辑模式下使用时却没有。因此,当我通过其他函数分配ngModel时,选择下拉列表的视图不会更新。这是我的HTML看起来的样子。

<select 
  class="form-control" 
  [(ngModel)]="selectedContentType" 
  [attr.disabled]="hideCollectionandContentType || hideContentTypeOnly ? '' : null" 
  required 
  (change)="contentTypeChanged(selectedContentType)">
  <option [ngValue]="undefined">
    Select Content Type
  </option>
  <option 
    *ngFor="let c of contentTypes" 
    [ngValue]="c">
    {{c.value}}
  </option>
</select>

对于每个对象,contentTypes的json看起来像这种格式。

{ key: '', value: ''}

例如,我正在阅读一个现有的表单,它应该显示来自API的数据。我正在设置这样的数据。

const selectedContentType = JSON.parse(res.BulkUpdate_SelectedContentType);
        this.selectedContentType = { key: selectedContentType.ContentTypeId, value: selectedContentType.ContentTypeName };

其设置格式正确,但选择下拉列表未更新。

angular angular-forms
1个回答
0
投票

如果你想设置下拉列表,你必须设置相同的对象引用,javascript中的对象通过引用比较,当你将selectedContentType设置为新对象时,即使它具有相同的属性和值,它也会考虑不同的值。

这是一个新的对象引用,它不是任何选项值的等价。

  this.selectedContentType = { key: selectedContentType.ContentTypeId, value: selectedContentType.ContentTypeName };

contentTypes = [
    {name:1,value:1},
    {name:2,value:2},
    {name:3,value:3},
    {name:4,value:4},
    ];

set() {
      // this.selectedContentType = {name:1,value:1}; // not working , new object refrences
      this.selectedContentType = this.contentTypes[0]; 
    }

如果要将所选项目设置为值4作为示例

this.selectedContentType = this.contentTypes.find(i => i.value == 4);

在上面的行中,我们在下拉选项列表中获得相同的对象引用。

stackblitz demo

© www.soinside.com 2019 - 2024. All rights reserved.