export interface User {
name: string;
address?: {
street?: string;
postcode?: string;
country?: Country;
}
}
export class Country {
name: string;
code: string;
}
我正在使用ng2-completer库在UI中附加国家/地区选择。
<div class="form-group" formGroupName="address">
<label for="">Country</label>
<ng2-completer
[(ngModel)]="searchStr"
[datasource]="dataService"
[minSearchLength]="0"
(selected)="onSelected($event)"
formControlName="country"
[class]="form-control">
</ng2-completer>
</div>
protected searchData = [
{ name: 'india', code: 'ind' },
{ name: 'australia', code: 'aus' },
{ name: 'sri lanka', code: 'sla' }
];
private searchStr: String;
private dataService: CompleterData;
private selectedCountry: Country;
constructor(
private _fb: FormBuilder,
private _cService: CompleterService
) {
this.dataService = _cService.local(this.searchData, 'name', 'name');
}
protected onSelected(selectedItem: CompleterItem) {
if(selectedItem) {
this.selectedCountry = selectedItem.originalObject;
console.log(this.selectedCountry);
// this logs the selectedCountry.
this.myForm['controls']['address']['controls']['country'].setValue(this.selectedCountry));
}
}
这里有两件事:
this.searchStr = this.selectedCountry.code;
在尝试上面的代码时,它会在UI中显示所选代码,并且在提交的表单中它会传递相同的字符串,但我希望在表单提交时它是一个对象。
this.myForm['controls']['address']['controls']['country'].setValue(this.selectedCountry));
使用上面的代码,它在表单提交时成功发送country对象,但是在UI中显示问题[object object]。
我希望它在UI中显示所选的字符串/代码,但在提交时,它应该发送国家/地区对象。怎么做到这一点?
答案 0 :(得分:0)
你可以尝试下面的内容:
将 searchStr 从string
更改为Country
并绑定[(ngModel)] = "searchStr.name"
答案 1 :(得分:0)
您可以创建一个隐藏元素,该元素将包含该对象并将被发送,而显示的数据保持不变:
<div class="form-group" formGroupName="address">
<label for="">Country</label>
<ng2-completer
[(ngModel)]="searchStr"
[datasource]="dataService"
[minSearchLength]="0"
(selected)="onSelected($event)"
[class]="form-control">
</ng2-completer>
<input
type="hidden"
formControlName="country">
</div>
答案 2 :(得分:0)
请尝试以下代码:
<ng2-completer
formControlName="captain"
(selected)="onSelected($event)"
[datasource]="captains"
[minSearchLength]="0"
></ng2-completer>
onSelected(event){
console.log(`Event: ${ JSON.stringify(event)}`)
}