0
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 中显示选定的字符串/代码,但在提交时这应该发送国家对象。如何做到这一点?

4

3 回答 3

0

你可以试试下面:

searchStrstringtoCountry和 in binding更改[(ngModel)] = "searchStr.name"

于 2017-06-19T07:06:12.660 回答
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>
于 2017-06-23T12:55:01.393 回答
0

试试下面的代码:

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

onSelected(event){
    console.log(`Event: ${ JSON.stringify(event)}`)
}
于 2017-08-16T03:24:36.250 回答