I am trying to get the autocomplete to display one parameter of object but save another and so far it doesn't seem to be behaving.
Code is as per Material2 Autocomplete site: Autocomplete
The difference is that [value] i want to save 'option.Id' and not 'option'.
The error is that while it records the option.Id it doesn't actually display the value in 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;
}
Try giving the autocomplete a model (example: myModel):
Here,
[ngValue]
givesmyModel
the value ofoption.Id
.When you retrieve the model
myModel
you will be gettingoption.Id
.If you need, you can help yourself by adding
(ngModelChange)="onChange($event)"
to your<md-autocomplete>
in order to manipulate data in the component.