使用 ngx Bootstraps onSelect 方法获取选定值的对象。示例:https ://stackblitz.com/run
change in ts :
import { Component } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { TypeaheadMatch } from 'ngx-bootstrap/typeahead/typeahead-
match.class';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
selectedOption;
groupSelected = {name: 'Alabama', value: 1};
statesComplex: any[] = [
{ id: 1, name: 'Alabama', value: 1, region: 'South' },
{ id: 2, name: 'Alaska', value: 2, region: 'West' },
{ id: 3, name: 'Arizona', value: 3, region: 'West' },
{ id: 4, name: 'Arkansas', value: 4, region: 'South' },
{ id: 5, name: 'California', value: 5, region: 'West' },
];
onSelect(event: TypeaheadMatch): void {
this.selectedOption = event.item;
this.groupSelected.name = event.item.name;
this.groupSelected.value = event.item.value;
}
}
html中的变化:
<pre class="card card-block card-header mb-3">Model:
{{groupSelected.value | json}}</pre>
<input [(ngModel)]="groupSelected.name"
[typeahead]="statesComplex"
typeaheadOptionField="name"
typeaheadGroupField="region"
(typeaheadOnSelect)="onSelect($event)"
class="form-control">