问题描述
ng-bootstrap typeahead 元素允许获取一组对象建议,然后选择一个,以便模型成为所选对象.
The ng-bootstrap typeahead element allows fetching an array of object suggestions and then selecting one so that the model becomes the selected object.
完整代码可以在这个 Plunkr 中看到.通过搜索美国州然后观察 model
输出来测试它.
The full code can be seen in this Plunkr. Test it by searching for a US state then observing the model
output.
这是模板:
<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>
当您搜索Alabama"时模型不会变成阿拉巴马州,而是
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"
}
在我的情况下,我希望将模型设为 Alabama
.我不想在表单中将图像和其他数据发送回服务器.
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.
我尝试使用 ng-bootstrap 提供的 (selectItem)
事件,并手动更改其中的值,但这不起作用.模型保持不变——一个对象而不是一个字符串!
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!.
即
selectItem(e: NgbTypeaheadSelectItemEvent, fubi: any ){
console.log("e.item.name", e.item.name);
this.addressForm.patchValue({
statename: e.item.name
});
}
我的表单的 statename
属性在以这种方式调用时不会更新
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
推荐答案
看起来您对 selectItem 事件走上了正轨.也许你只是没有完全理解语法?
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:
- 删除 ngModel 引用
- 将它替换为对触发 selectItem 事件时要运行的函数的引用(此函数可以适当地设置模型"……或状态名称"……无论您的船漂浮什么)
像这样:
<input id="typeahead-template"
type="text"
class="form-control"
(selectItem)="setModel($event)"
[ngbTypeahead]="search"
[resultTemplate]="rt"
[inputFormatter]="formatter" />
然后,在你的 typeahead-template.ts 文件中,添加函数:
and then, in your typeahead-template.ts file, add the function:
setModel(e: NgbTypeaheadSelectItemEvent, fubi: any) {
this.model = e.item.name;
}
我用这些模组分叉了你的Plunkr,它设置了模型"根据需要对阿拉巴马州"进行值...您可能可以从那里开始做任何您需要做的事情.希望有帮助!
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!
这篇关于我如何使用预先输入来获取/呈现对象但接收和响应字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!