【问题标题】:how to set value for input field from component in angular2如何从angular2中的组件设置输入字段的值
【发布时间】:2017-06-19 06:55:56
【问题描述】:
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 中显示选定的字符串/代码,但在提交时这应该发送国家对象。如何做到这一点?

【问题讨论】:

  • 看到 setValue 没有问题。 :) 现在它显示国家名称并提交相同的。 + 它显示国家对象(但在 UI 中不好看到 [object Object])并提交对象。但我想要的是选择它应该在 UI 中显示国家名称,但在提交时它应该通过国家对象。

标签: angular angularjs-ng-form ng2-completer


【解决方案1】:

您可以创建一个隐藏元素,该元素将包含对象并将被发送,而显示的数据保持不变:

<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】:

    试试下面的代码:

    <ng2-completer 
       formControlName="captain" 
       (selected)="onSelected($event)"
       [datasource]="captains" 
       [minSearchLength]="0"
    ></ng2-completer>
    
    onSelected(event){
        console.log(`Event: ${ JSON.stringify(event)}`)
    }
    

    【讨论】:

      【解决方案3】:

      你可以试试下面:

      searchStrstring 更改为 Country 并绑定 [(ngModel)] = "searchStr.name"

      【讨论】:

      • 使用它设置带有字符串值的字段,并通过提交它发送相同的字符串。但我希望它发送国家对象。
      猜你喜欢
      • 1970-01-01
      • 2017-12-25
      • 2021-10-03
      • 1970-01-01
      • 2011-01-06
      • 2011-11-28
      • 1970-01-01
      相关资源
      最近更新 更多