绑定到对象的属性在Angular 2中不起作用
问题描述:
我对Angular 2属性绑定有着非常奇怪的行为。绑定到对象的属性在Angular 2中不起作用
首先,这是一个存储类:
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>
这里的的<select>
标签option
是行不通的结合[value]="s"
!它将selectedStore
设置为某个空对象(?),它在<small>
标记中显示空的文本,并在控制台(selectionChanged()
)中记录:DEBUG: [object Object]
。但是{{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"
按预期工作。我遵循了文档,没有提到这种限制。这是一个错误?或者我错过了什么?
答
[value]
只支持字符串值作为绑定值。改为使用[ngValue]
,它可以绑定对象。
答
我有同样的问题,你可以试试我的解决方案:
<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]);
}
我想这应该在官方的文档,它并不像这个帖子中清楚地记录。 – Titan