首页 > 解决方案 > 如何将 Ngx-bootstrap typeahead 中的自动完成数据绑定到输入字段

问题描述

我有以下返回数据的预输入

<input [(ngModel)]="model" [class.is-invalid]="searchFailed" [inputFormatter]="inputFormatBandListValue"
                 [ngbTypeahead]="search" [resultFormatter]="resultFormatBandListValue" class="form-control"
                 id="typeahead-http"
                 name="Search" placeholder="Search" type="text" value="search"/>
          <!--              <small *ngIf="searching" class="form-text text-muted">searching...</small>-->
          <img *ngIf="searching" alt="Loading Icon" src="assets/img/user/loading.gif">
          <div>
            <p>{{model | json}}</p>
          </div>
<input  class="form-control" id="manufyear" name="manufyear" type="text">
<input  class="form-control" id="location" name="location" type="text">

json格式 {"Vehicle Name": "TOYOTA PRADO","MANUFACTURED YEAR":"2010", "LOCATION":"TOKYO"}

我如何绑定其他输入字段,以便当用户从自动完成输入中选择一个 vlue 时,其他字段将填充来自该选择的数据。我希望是清楚的家伙。

标签: angularangular-ngmodel

解决方案


您没有使用NGX-Bootstrap(您使用的是NG Bootstrap),它们是完全不同的库。

您可以使用selectItem 事件解决您的问题,该事件可在ngbTypeahead Directive

HTML:

<input [(ngModel)]="model" 
       [class.is-invalid]="searchFailed" 
       [inputFormatter]="inputFormatBandListValue"
       [ngbTypeahead]="search" 
       [resultFormatter]="resultFormatBandListValue" 
       class="form-control"
       id="typeahead-http"
       name="Search"
       placeholder="Search" 
       type="text"
       (selectItem)="onItemSelect($event)" <--------------- add this
       value="search" />
<img *ngIf="searching" alt="Loading Icon" src="assets/img/user/loading.gif">
<div>
    <p>{{model | json}}</p>
</div>
<input  class="form-control" id="manufyear" name="manufyear" type="text">
<input  class="form-control" id="location" name="location" type="text">

TS:

onItemSelect(event: NgbTypeaheadSelectItemEvent) {
    const selectedObj = event.item // this is the selected object from the typeahead

    // now you can set the other inputs values here...
}

推荐阅读