【发布时间】:2017-03-27 11:22:43
【问题描述】:
我在使用 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 设置为某个空对象(?),它在<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" 按预期工作。我已经关注了文档,没有提到这种限制。这是一个错误吗?还是我错过了什么?
【问题讨论】:
标签: angularjs angular property-binding