绑定到对象的属性在Angular 2中不起作用

时间:2016-11-13 20:10:30

标签: angularjs angular property-binding

我对Angular 2属性绑定有非常奇怪的行为。

首先,这是一个Store类:

export class Store {
    id: number;
    name: string;
    address: string;
}

这是组件代码:

export class MyBuggyComponent implements OnInit {

  stores: Store[];
  selectedStore: any;
  error: any;

  constructor(private myDataService: MyDataService) { }

  ngOnInit() {
    this.myDataService.getStores().subscribe(
      stores => this.stores = stores,
      error => { this.error = error; console.log(this.error); });
  }

  selectionChanged(value: any){
    console.log("DEBUG: " + value);
  }
}

这是让我疯狂的模板!

<form>
  <div class="form-group">
    <label for="store">Select store:</label>
    <select class="form-control custom-select" id="store" name="store" required 
      [(ngModel)]="selectedStore" (change)="selectionChanged($event.target.value)">
      <option *ngFor="let s of stores" [value]="s">{{s.name}}</option>
    </select>
    <small class="form-text text-muted" *ngIf="selectedStore">Address: {{selectedStore.address}}</small>
  </div>
</form>

此处[value]="s" option标记的绑定<select>不起作用!它将selectedStore设置为某个空对象(?),它在Address:标记中显示空<small>文本,并在控制台中记录:DEBUG: [object Object](在selectionChanged()中)。但{{s.name}}插值按预期工作(在选择框内显示名称)。

现在看一下:如果我对模板进行了以下修改,它就会按预期工作:

  <option *ngFor="let s of stores" [value]="s.address">{{s.name}}</option>
</select>
<small class="form-text text-muted" *ngIf="selectedStore">Address: {{selectedStore}}</small>

现在绑定工作,地址记录在控制台中,并且也正确显示在<small>标记中。因此绑定[value]="s"不起作用(实际上提供了一些奇怪的对象&#39;值),但绑定[value]="s.address"按预期工作。我已按照文档进行操作,并未提及此类限制。这是一个错误吗?或者我错过了什么?

2 个答案:

答案 0 :(得分:2)

[value]仅支持字符串值作为绑定值。使用[ngValue]代替,它可以绑定对象。

答案 1 :(得分:-1)

我有同样的问题,你可以尝试我的解决方案:

<select class="form-control custom-select" id="store" name="store" required 
  [(ngModel)]="selectedStore" (change)="selectionChanged($event.target.value)">
  <option *ngFor="let s of stores; let i = index" value="{{i}}">{{s.name}}</option>
</select>

// .ts
selectionChanged(value: any){
   // this.selectedStore = position in stores
   console.log(this.stores[this.selectedStore]);
}