我有一个与客户打交道的Angular 2应用程序和一个弹簧休息后端。客户对象有一个客户类型,也是一个对象,我在客户表单上下拉工作,以便将对象存储为值,但是我无法弄清楚如何选择正确的客户类型将现有客户加载到表单中时。
<select class="form-control" required [(ngModel)]="customer.customerType" >
<option *ngFor="let ct of customerTypes" [ngValue]="ct">{{ct.customerType}}</option>
</select>
在上面的代码段中,如果客户已有客户类型,则下拉列表不会选择任何值。我记得使用ngOptions解决了angular1的相同问题:
<select ng-model="customer.customerType"
ng-options="customerType.customerType for customerType in customerTypes
track by customerType.customerType" >
</select>
所以,我的问题是,如何复制Angular1在Angular 2中解决这个问题的方式
答案 0 :(得分: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>
答案 1 :(得分: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]);
}
}
我已将数组硬编码到选择器中,但如果您愿意,您当然可以使用您的自定义类型向组件添加输入参数
然后您可以使用上面这样的组件:
<custype-selector (select)="custype = $event"></custype-selector>
答案 2 :(得分:0)
我采用了稍微笨重的方法来替换CustomerType对象中返回的CustomerType实例,并将其保存在CustomerType数组中。只有从支持的客户和客户类型返回后才能执行此操作:
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;
}
}
}
}