Select by name and enter id in md autocomplete input in angular 4 app material
I have an angular 4 app with material design. In this application, I have a form with an autocomplete field.
This is my html code:
<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:
console.log("project = " + this.selectProjectForNewCollab);
So, I have projects
three fields: {id: "1", name: "test", photo: "test"}
. I want to select a project by its name, but bring it back. Actually, I chose a name, but I got a name at the end. If I change [value]="project.id"
, I get an ID, but this is the ID that is displayed in the input.
So you know how can I do to get the id but select by name and display the name in the input?
source to share
For md-autocomplete
you must have separate control
and display
. md-aucomplete
provides an displayWith
api that can be used to select the field to be displayed in the dropdown / selected field.
For your code, it looks something like this:
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 add displanFn
:
displayFn(project): string {
console.log(project);
return project ? project.name : project;
}
Please do not have that in html binding with the whole object now [value]="project"
, which allows to show one property, but get all the properties of the object behind the scenes, from there you can select id
of the selected element.
source to share