export interface User {
name: string;
address?: {
street?: string;
postcode?: string;
country?: Country;
}
}
export class Country {
name: string;
code: string;
}
I am using ng2-completer library to attach the country selection in the 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));
}
}
Two things are here:
this.searchStr = this.selectedCountry.code;
On trying above code it shows the selected code in the UI and also in the submitted form it passes the same string, but I want this to be an object when the form gets submitted.
this.myForm['controls']['address']['controls']['country'].setValue(this.selectedCountry));
With above code it successfully sends the country object when form gets submitted, but issue is in UI it shows [object Object].
I want it to display the selected string/code in the UI but on submission this should send the country object. How to achieve this?
You can create a hidden element that will contain the object and will be sent, while the displayed data remains without change: