2016-11-13 63 views
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"按預期工作。我遵循了文檔,沒有提到這種限制。這是一個錯誤?或者我錯過了什麼?

回答

2

[value]只支持字符串值作爲綁定值。改爲使用[ngValue],它可以綁定對象。

+0

我想這應該在官方的文檔,它並不像這個帖子中清楚地記錄。 – Titan

0

我有同樣的問題,你可以試試我的解決方案:

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