我有一个绑定到客户数组的Angular5 <select>。如下所示:
<select class="form-control" [ngModel]="record.customer_id" (ngModelChange)="setCustomer($event)" name="customer_id">
<option *ngFor="let x of customers" [ngValue]="x.id">{{x.name}}</option>
</select>在事件函数中,我以‘setCustomer’的形式获得了一个客户的id。
属性record.customer_id是number类型,而不是object类型。有没有办法在setCustomer方法中获取整个customer实体,同时保留到record.customer_id的绑定?
我在Angular docu上找到了一种[compareWith]的方法,所以我尝试了:
<select class="form-control" [compareWith]="compareCustomer" [ngModel]="record.customer_id" (ngModelChange)="setCustomer($event)" name="customer_id">
<option *ngFor="let x of customers" [ngValue]="x">{{x.name}}</option>
</select>和
compareCustomer(c1: customer, c2: number) : boolean {
if (c1 == null || c1 == undefined) {
return false;
}
if (c1.id == c2) {
return true;
}
return false;
}不起作用。当我选择任何选项时,setCustomer将被执行,record.customer_id将获得选定的id。但是,在select失去焦点后,选定的选项将重置为空白。
有一个我想要避免的变通方法(在customers数组中迭代并通过id手动匹配):
setCustomer(event) {
this.record.customer_id = Number.parseInt(event);
customers.forEach(c => {
if (c.id === this.record.customer_id) {
// some logic with selected customer
}
});
}有什么建议吗?
谢谢!
发布于 2018-02-12 17:57:43
不绑定customer_id,而是绑定整个对象:
<select class="form-control" [ngModel]="record" (ngModelChange)="setCustomer($event)" name="customer_id">
<option *ngFor="let x of customers" [ngValue]="x">{{x.name}}</option>
</select>https://stackoverflow.com/questions/48743552
复制相似问题