Value not displayed for Material2 Autocomplete
I'm trying to get autocomplete to display one parameter of an object, but keep another, and so far this doesn't seem to behave.
Code according to Material2 Autocomplete site: Autocomplete
The difference is that [value] I want to keep the .Id 'option, not the' option '.
The error is that while it is writing the parameter. If it doesn't display the value in the input field (leaves it blank).
my-comp.html
<md-input-container>
<input type="text" mdInput [formControl]="myControl" [mdAutocomplete]="auto">
</md-input-container>
<md-autocomplete #auto="mdAutocomplete" [displayWith]="displayFn">
<md-option *ngFor="let option of filteredOptions | async" [value]="option.Id">
{{ option.name }}
</md-option>
</md-autocomplete>
my-comp.ts
class MyComp implements OnInit {
myControl = new FormControl();
options = [
new User('Mary', 1),
new User('Shelley', 2),
new User('Igor', 3)
];
filteredOptions: Observable<User[]>;
ngOnInit() {
this.filteredOptions = this.myControl.valueChanges
.startWith(null)
.map(user => user && typeof user === 'object' ? user.name : user)
.map(name => name ? this.filter(name) : this.options.slice());
}
filter(name: string): User[] {
return this.options.filter(option => new RegExp(`^${name}`, 'gi').test(option.name));
}
displayFn(user: User): string {
return user ? user.name : user;
}
}
class User {
name: string;
id: number;
constructor(name: string, id: number)
this.name = name;
this.id = id;
}
source to share
Try giving autocomplete to the model (example: myModel):
<md-autocomplete #auto="mdAutocomplete" [displayWith]="displayFn" [(ngModel)]="myModel">
<md-option *ngFor="let option of filteredOptions | async" [ngValue]="option.Id">
{{ option.name }}
</md-option>
</md-autocomplete>
Here [ngValue]
gives myModel
meaning option.Id
.
When you receive the model myModel
, you will receive option.Id
.
If you need to, you can help yourself by adding (ngModelChange)="onChange($event)"
to yours <md-autocomplete>
to manipulate the data in the component.
source to share
you can filter from options
using displayWith
from md-autocomplete
to find user.name
based on user.id
bound to md-option
, here you need to use bind(this)
to access component data.
<md-autocomplete #auto="mdAutocomplete" [displayWith]="displayFn.bind(this)">
and filter on displayFn
function
displayFn(id: number): string {
if (!id) return '';
let index = this.options.findIndex(option => option.id === id);
return index === -1 ? '' : this.options[index].name;
}
Send out a demonstration plunkera .
Comment: in your template you are using Id
, but in your class User
this Id
. I think this could also cause an empty string to be set, and if you correct that typo, it user.id
will be set to md-input
.
source to share