【问题标题】:How to set typeahead default/initial value for Angular 2 ng-bootstrap?如何为 Angular 2 ng-bootstrap 设置预先输入的默认/初始值?
【发布时间】:2017-01-12 20:04:19
【问题描述】:

我正在使用来自 ng-bootstrap.github.io 的模板作为结果示例。

这工作得很好。我用它让用户在表单中输入城市。

问题在于编辑用户详细信息。我不确定如何为该用户填充以前保存的城市。这就是我在 HTML 中所拥有的:

<template #rt let-r="result" let-t="term">
    {{ r.name}}
</template>
<input (blur)="lostFocus($event)" class="form-control" formControlName="city_obj" type="text" [(ngModel)]="typeaheadModel" [ngbTypeahead]="search" [resultTemplate]="rt" [inputFormatter]="formatter" (selectItem) = "selectItem($event)">

这是来自组件:

search = (text$: Observable<string>) =>
text$
.debounceTime(200)
.map(term => term === '' ? []
    : this.cities.filter(v => new RegExp(term, 'gi').test(v.name)).slice(0, 10));
formatter = (x: {name: string}) => x.name;

我使用模型驱动的表单。

在数据库中,我只保存用户的城市 ID,因为城市在单独的表中。

所以,在表单生成器中,我有 city_id 字段和 city_obj。

API 只会保存 city_id 而忽略 city_obj。

我使用 selectItem 事件来设置组件中的 city_id 字段。

那么,如何设置之前保存的城市来输入和保持预输入功能?

【问题讨论】:

    标签: angular ng-bootstrap


    【解决方案1】:

    像这样在 ngmodel 的构造函数或 ngOnInit 方法中设置数据。

    constructor(){
       this.typeaheadModel = {
         name : "test name"
       }
    }
    
    

    【讨论】:

      【解决方案2】:

      自己发现的。

      我只需要将同一个对象设置为表单控件,但在 debounceTime 之后。

      编辑:因为这是很久以前的事了,我不知道这是否是正确的方法。由于对此有很多兴趣,我找到了我使用它的项目。以下是我当时设置 typeahead 值的方法,效果很好:

      this.form.controls['city_obj'].setValue({id:this.formData.city.id, name:this.formData.city.name});
      

      【讨论】:

      • 解决后能否更新源代码? @igor
      • 这里也一样。你能更新源代码吗?我在“编辑”模式下遇到了同样的问题。不确定如何使用现有值设置预先输入。谢谢。
      猜你喜欢
      • 2012-11-26
      • 2016-11-18
      • 1970-01-01
      • 2014-01-23
      • 2019-09-24
      • 2018-02-06
      • 1970-01-01
      • 2017-06-11
      • 2017-06-17
      相关资源
      最近更新 更多