I'm facing a problem with my Angular Material 2 Autocomplete fields.
This is my setup:
hardwareCreate.component.ts
myControl: FormControl = new FormControl();
availableFirmware = [];
filteredFirmware: Observable<any[]>;
selectedFirmware = null;
selectedFirmwareName = '';
this.availableFirmware = [];
this.terminalService.getFirmware().subscribe(firmware => {
this.availableFirmware = firmware.firmware;
});
this.filteredFirmware = this.myControl.valueChanges
.pipe(
startWith(''),
map(val => this.filterFirmware(val))
);
filterFirmware(val: any): any[] {
return this.availableFirmware.filter(firmware => {
return firmware.name.toLowerCase().indexOf(val.toLowerCase()) > -1;
});
}
hardwareCreate.component.html
<div class="form-group">
<mat-form-field class="example-full-width">
<input type="text" placeholder="Firmware auswählen" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto1" [(ngModel)]="selectedFirmwareName">
<mat-autocomplete #auto1="matAutocomplete">
<mat-option *ngFor="let firmware of filteredFirmware | async" [value]="firmware._id">
{{ firmware.name }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</div>
So my problem now is, that when I type I get the firmware.name attribute which is correct and looks like this:
But when I now select a firmware, the value
changes to the _id
of firmware
.
So I could change [value]="firmware._id"
to [value]="firmware.name"
but I need the ID for my mongodb ->
firmware: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Firmware'
},
Question: How can I change the display value to the name, but still get the Id for my Database when the user selects a specific firmware?
The solution now is a combination of both of vsoni and JEYs answers. The problem at the end was, that val
was an object. By converting it to a string, anything works like a charme!
Thanks to both of you!
firmware._id