2016-06-09 88 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