I am currently working on creating an Angular Material Autocomplete feature. At the moment, I have successfully displayed the options and when selected, the correct name is inserted into the input field.
However, my next task is to enable filtering of the options as the user types. I tried following the Angular Material tutorial but encountered errors along the way.
One recurring error message I receive is:
An argument for 'callbackfn' was not provided.
This issue arises when attempting to implement the filteredOptions functionality.
Furthermore, once I complete this step, the subsequent challenge would be to display the name in the first input field and the corresponding phoneNumber in the adjacent input field. I'm currently seeking suggestions on how best to approach this problem!
IDriverDate interface:
export interface IDriverData {
name: string;
phone: string;
}
messages.component.ts:
My driver data is stored within driverData array. Although unclear why I need to use filteredOptions instead of directly manipulating the data.
driverData: IDriverData[];
filteredOptions: Observable<IDriverData[]>;
ngOnInit(): void {
this.getMessages();
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith(''),
map(driver => typeof driver === 'string' ? driver : driver.name),
map(name => name ? this._filter(name) : this.driverData.slice())
);
}
displayFn(driver): string {
return driver ? driver.name : driver;
}
private _filter(name: string): IDriverData[] {
const filterValue = name.toLowerCase();
return this.driverData.filter(driver => driver.name.toLowerCase().indexOf(filterValue) === 0);
}
messages.component.html:
<div>
<mat-card>
<mat-card-title>Verstuur een bericht:</mat-card-title>
<mat-divider></mat-divider>
<mat-card-content>
<div class="input">
<mat-form-field>
<input matInput placeholder="Naam" [(ngModel)]="name" [formControl]="myControl" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
<mat-option *ngFor="let driver of driverData" [value]="driver">
{{driver.name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Telefoonnummer" type="tel" [(ngModel)]="number">
</mat-form-field>
</div>
<mat-divider class="subdivider"></mat-divider>
<div class="message">
<mat-form-field>
<textarea id="message" matInput placeholder="Bericht: " rows=10 [(ngModel)]="content"></textarea>
</mat-form-field>
</div>
</mat-card-content>
<mat-card-actions>
<button mat-raised-button (click)="sendMessages()">Verstuur</button>
</mat-card-actions>
</mat-card>
</div>