2016-06-09 132 views
6

我有一個Angular 2應用程序正在處理客戶和春季休息後端。客戶對象有一個客戶類型,這也是一個對象,我有客戶表單上的下拉菜單,因此對象被存儲爲值,但我無法弄清楚如何選擇正確的客戶類型現有客戶被加載到表單中。Angular2選擇對象的選項

<select class="form-control" required [(ngModel)]="customer.customerType" > 
    <option *ngFor="let ct of customerTypes" [ngValue]="ct">{{ct.customerType}}</option> 
</select> 

在如果客戶已經有一個客戶類型上面的代碼,然後在下拉不會選擇任何值。我記得有與angular1這是解決使用ngOptions同樣的問題:

<select ng-model="customer.customerType" 
     ng-options="customerType.customerType for customerType in customerTypes 
     track by customerType.customerType" > 
</select> 

所以,我的問題是,如何複製Angular1解決了角2

+2

只需將默認值分配給'customer.customerType'即可。 'ngValue'和'customer.customerType'需要指向同一個對象實例,而不僅僅指向兩個具有相同內容的對象。 –

+1

我意識到它需要相同的對象實例,而不是具有相同內容的對象,但我想知道是否有一種方法可以通過類似於java中的比較器的方式傳遞select,它會使用以評估對象實例是否相同。我已經結束了在其他調用中返回的實例,以及來自select選項的等價對象,這感覺真的很笨重。 – Drew

+0

[將選擇元素綁定到Angular 2中的對象]可能的重複(https://stackoverflow.com/questions/35945001/binding-select-element-to-object-in-angular-2) –

回答

0

我已經採取了更換是在我的客戶對象中返回,與該CustomerType數組中舉行CustomerType的實例的稍微笨拙的辦法。這隻能做一次無論是客戶和CustomerTypes已經從返回的支持:

ngOnInit() { 
    let id = this._routeParams.get('id'); 
    this._service.getCustomer(id).subscribe(customer => { 
     this.customer = customer; 
     this.updateCustomerType(); 
    }); 
    this._service.getCustomerTypes().subscribe(customerTypes =>{ 
     this.customerTypes = customerTypes; 
     this.updateCustomerType(); 
    }); 
} 
private updateCustomerType(): void{ 
    if(this.customer.customerType != null && this.customerTypes.length != null){ 
    for (var customerType of this.customerTypes) { 
     console.log("Customer Type: ", customerType); 
     if(this.customer.customerType.id == customerType.id){ 
     this.customer.customerType = customerType; 
     } 
    } 
    } 
} 
0

這個問題的方式,我建議你更改方法建立這個,通過創建一個選擇組件:

import {Component, Output, EventEmitter} from 'angular2/core'; 

@Component({ 
    selector: 'custype-selector', 
    template: ` 
    <div> 
     <label>Cust type</label> 
     <select #sel (change)="select.emit(sel.value)"> 
      <option *ngFor="#custype of customertypes"> {{custype}} </option> 
     </select> 
    </div>` 
}) 
export class CusTypeSelector { 
    @Output() select = new EventEmitter(); 
    customertypes= ["type1", "type2"] 

    ngOnInit(){ 
     this.select.emit(this.customertypes[0]); 
    } 
} 

我硬編碼的數組選擇,但你當然可以輸入參數與customertypes如果你喜歡

添加到組件

然後你可以使用上面的組件是這樣的:

<custype-selector (select)="custype = $event"></custype-selector> 
+0

謝謝,我喜歡看這一點,並會放棄它。出於興趣,是否有理由說客戶類型可以作爲參數提供,而包括從後端REST API獲取客戶類型的服務?我可以看到下拉列表組件能夠獲取它自己的選項列表是有用的。 – Drew

7

我有同樣的問題,我解決了它這種方式:

<select class="form-control" required [(ngModel)]="customer.customerType" > 
    <option *ngFor="let ct of customerTypes" 
     [ngValue]="ct" 
     [attr.selected]="customer.customerType.customerType==ct.customerType ? true : null" 
     >{{ct.customerType}}</option> 
</select> 

由於Günter Zöchbauer