[英]Choose by name et get the id in md-autocomplete input in angular 4 material application
I have an angular 4 application with material design.我有一个带有材料设计的 angular 4 应用程序。 In this application I have a form with an autocomplete field.
在这个应用程序中,我有一个带有自动完成字段的表单。
This is my html code :这是我的 html 代码:
<div class="form-group">
<md-input-container>
<input mdInput type="text" mdInput [mdAutocomplete]="project" [formControl]="projectCtrl" placeholder="Choose a project" [(ngModel)]="selectProjectForNewCollab" name="selectProjectForNewCollab">
</md-input-container>
<md-autocomplete #project="mdAutocomplete">
<md-option *ngFor="let project of filteredProjects | async" [value]="project.name">
{{ project.name }}
</md-option>
</md-autocomplete>
</div>
And my ts code :还有我的 ts 代码:
console.log("project = " + this.selectProjectForNewCollab);
So, I have projects
with 3 fields : {id: "1", name: "test", photo: "test"}
.所以,我有 3 个字段的
projects
: {id: "1", name: "test", photo: "test"}
。 I want to choose a project by its name but get back the id in return.我想按名称选择一个项目,但要取回 id 作为回报。 Actually, I have choose with the name but I get the name at the end.
实际上,我已经选择了名字,但最后我得到了名字。 If I change the
[value]="project.id"
, I get the id but it's teh id which is displayed in the input.如果我更改
[value]="project.id"
,我会得到 id 但它是显示在输入中的 id 。
So, do you know how I can do to get the id but choose by name and display the name in the input ?那么,您知道如何获取 id 但按名称选择并在输入中显示名称吗?
You need to have separate control
and display
for md-autocomplete
.您需要对
md-autocomplete
进行单独的control
和display
。 md-autocomplete
provides displayWith
api which can be used to pick which field to show in dropdown/selected field. md-autocomplete
提供displayWith
api,可用于选择要在下拉/选定字段中显示的字段。
For your code, it would look something like following:对于您的代码,它将类似于以下内容:
html: html:
<md-input-container>
<input mdInput placeholder="Project"
[(ngModel)]="selectProjectForNewCollab" (ngModelChange)="setProject(project)"
[mdAutocomplete]="project" [formControl]="stateCtrl">
</md-input-container>
<md-autocomplete #project="mdAutocomplete" [displayWith]="displayFn">
<md-option *ngFor="let project of filteredStates | async" [value]="project" >
{{ project.name }}
</md-option>
</md-autocomplete>
In component.ts, have to add the displanFn
:在 component.ts 中,必须添加
displanFn
:
displayFn(project): string {
console.log(project);
return project ? project.name : project;
}
Please note that, in html, the binding is with the whole object now [value]="project"
, which allows to show one property, but get all properties of the object behind the scenes, from there, you can pick the id
of the selected item.请注意,在HTML中,结合是现在整个对象
[value]="project"
,这使得显示一个属性,但得到的幕后对象的所有属性,从那里,你可以挑选的id
的所选项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.