Reputation: 487
I am using Angular bootstrap typeahead plugin to choose a value from a list.
However it does not work when I type whole value and click outside.
http://plnkr.co/edit/WjHkhPJVZXMMF79apiIF?p=preview
<ng-template #rt let-r="result" let-t="term">
<img [src]="'https://upload.wikimedia.org/wikipedia/commons/thumb/' + r['flag']" width="16">
{{ r.name}}
</ng-template>
<label for="typeahead-template">Search for a state:</label>
<input id="typeahead-template" type="text" class="form-control" [(ngModel)]="model" [ngbTypeahead]="search" [resultTemplate]="rt"
[inputFormatter]="formatter" />
<hr>
<pre>Model: {{ model | json }}</pre>
Typescript
import {Component} from '@angular/core';
import {Observable} from 'rxjs';
import {debounceTime, map} from 'rxjs/operators';
interface IStateData {
name: string;
flag: string;
}
const statesWithFlags: {name: string, flag: string}[] = [
{'name': 'Alabama', 'flag': '5/5c/Flag_of_Alabama.svg/45px-Flag_of_Alabama.svg.png'},
{'name': 'Alaska', 'flag': 'e/e6/Flag_of_Alaska.svg/43px-Flag_of_Alaska.svg.png'},
{'name': 'Arizona', 'flag': '9/9d/Flag_of_Arizona.svg/45px-Flag_of_Arizona.svg.png'}
];
@Component({
selector: 'ngbd-typeahead-template',
templateUrl: 'src/typeahead-template.html',
styles: [`.form-control { width: 300px; }`]
})
export class NgbdTypeaheadTemplate {
public model: IStateData = {};
search = (text$: Observable<string>) =>
text$.pipe(
debounceTime(200),
map(term => term === '' ? []
: statesWithFlags.filter(v => v.name.toLowerCase().indexOf(term.toLowerCase()) > -1).slice(0, 10))
);
formatter = (x: {name: string}) => x.name;
}
When I select a item from a list or using tab key it works fine. Its setting the model value properly.
Issue: When I type whole city or pasted the value and click outside it does not work. It is basically not setting the item when i Blur on the type ahead
Model object not set properly and it converted to string here.
Note: I need similar to this one in Ngx bootstrap. https://valor-software.com/ngx-bootstrap/#/typeahead#on-blur But they have other open issue which failed to initialize the data.
Upvotes: 0
Views: 2877
Reputation: 27363
Add Blur Event to Your Input
<input id="typeahead-template" type="text" class="form-control"
[(ngModel)]="model"
[ngbTypeahead]="search"
[resultTemplate]="rt"
[inputFormatter]="formatter"
(blur)="onBlur(model)" />
Then Define this method in your ts file
onBlur(search) {
statesWithFlags.forEach(data => {
if (search.toLowerCase() === data.name.toLowerCase()) {
this.model = data;
}
})
}
Check this working Example
http://plnkr.co/edit/V29qxa?p=preview
Upvotes: 2