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

3
我是一个有用的助手,可以为您翻译文本。
我遇到了与Angular 2属性绑定相关的非常奇怪的行为。
首先,这是一个Store类:
export class Store {
    id: number;
    name: string;
    address: string;
}

This is component code:

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>

这里 <select> 标签的 option 上绑定的 [value]="s" 不起作用了!它会将 selectedStore 设置为某个空对象(?), 在 <small> 标签中显示空的 Address: 文本, 并在控制台中输出 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"不起作用(实际上会给出一些奇怪的“对象”值),但绑定[value]="s.address"按预期工作。我遵循了文档,没有提到这种限制。这是一个错误吗?还是我漏掉了什么?
2个回答

3

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


我认为这应该在官方文档中得到清晰的记录,但截至本帖发布时还没有。 - Titan

-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]);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接