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));
使用上面的代码,它在提交表单时成功发送国家对象,但问题是在 UI 中它显示 [object Object]。
我希望它在 UI 中显示选定的字符串/代码,但在提交时这应该发送国家对象。如何做到这一点?