我该如何使用typeahead来获取/呈现对象,但是接受并使用字符串进行响应? [英] How can I use typeahead to fetch/present objects but take in and respond with strings?

查看:103
本文介绍了我该如何使用typeahead来获取/呈现对象,但是接受并使用字符串进行响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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>

当您搜索阿拉巴马州"时,该模型不会变成阿拉巴马州,而是

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:

  1. 删除ngModel参考
  2. 将其替换为在激发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;
}

我通过这些mods 分叉了您的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!

这篇关于我该如何使用typeahead来获取/呈现对象,但是接受并使用字符串进行响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆