how to set value for input field from component in angular2

5.9k Views Asked by At
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?

3

There are 3 best solutions below

0
On

You can create a hidden element that will contain the object and will be sent, while the displayed data remains without change:

<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>
0
On

Try the following code:

<ng2-completer 
   formControlName="captain" 
   (selected)="onSelected($event)"
   [datasource]="captains" 
   [minSearchLength]="0"
></ng2-completer>

onSelected(event){
    console.log(`Event: ${ JSON.stringify(event)}`)
}
1
On

Can you try below:

change searchStr from string to Country and in binding [(ngModel)] = "searchStr.name"