问题
The ng-bootstrap typeahead element allows fetching an array of object suggestions and then selecting one so that the model becomes the selected object.
The full code can be seen in this Plunkr. Test it by searching for a US state then observing the model
output.
Here is the 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>
When you search for "Alabama" the model does not become Alabama, but rather
{
"name": "Alabama",
"flag": "5/5c/Flag_of_Alabama.svg/45px-Flag_of_Alabama.svg.png"
}
In my situation, I would like to get the model as Alabama
. I don't want to send the image and other data back to the server in my form.
I've tried using the (selectItem)
event provided by ng-bootstrap, and manually changing value in it but this does not work. The model remains the same - an object and not a string!.
i.e.
selectItem(e: NgbTypeaheadSelectItemEvent, fubi: any ){
console.log("e.item.name", e.item.name);
this.addressForm.patchValue({
statename: e.item.name
});
}
My form's statename
property is not updating when called this way
Any ideas why not ? I've tried all the obvious ones, I believe
回答1:
It looks like you're on the right track with the selectItem event. Maybe you just didn't quite get the syntax right?
In the input definition, you probably want to:
- remove the ngModel reference
- replace it with a reference to the function you want to run when the selectItem event is fired (this function can set "model" appropriately...or "statename" perhaps...whatever floats your boat)
like so:
<input id="typeahead-template"
type="text"
class="form-control"
(selectItem)="setModel($event)"
[ngbTypeahead]="search"
[resultTemplate]="rt"
[inputFormatter]="formatter" />
and then, in your typeahead-template.ts file, add the function:
setModel(e: NgbTypeaheadSelectItemEvent, fubi: any) {
this.model = e.item.name;
}
I forked your Plunkr with these mods, and it sets the "model" value to "Alabama" as desired...you can probably take it from there to do whatever you need to do. Hope that helps!
来源:https://stackoverflow.com/questions/47643662/how-can-i-use-typeahead-to-fetch-present-objects-but-take-in-and-respond-with-st