I have made a component for autocomplete and use it wherever in my project.
autocomplete.component.html:
<mat-form-field class="example-full-width">
<mat-label> {{label}}</mat-label>
<input type="text" aria-label="Number" matInput [matAutocomplete]="auto"
[formControl]="myControl">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{option.Text}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
autocomplete.component.ts
export class AutocompleteComponent implements OnInit {
filteredOptions: Observable<SelectedListItem[]>;
@Output() public onChange: EventEmitter<any> = new EventEmitter();
@Input() public label: string = "Select";
@Input() public options: any[];
@Input() public mycontrol: FormControl;
myControl = new FormControl();
constructor() { }
ngOnInit() {
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith(''),
map(value => {
if (value.length > 2) {
return this._filter(value);
} else {
return null;
}
})
);
}
displayFn(item: SelectedListItem) {
try { return item.Text; }
catch{ }
}
private _filter(value: string): any[] {
var result = this.options.filter(option =>
option.Text.toLowerCase().includes(value.toLowerCase()));
this.onChange.emit(result);
return result;
}
}
Now you can use autocomplete in any component:
<app-autocomplete (onChange)="getFilterOptions($event,'Numbers')" formControlName="Numbers" [options]="options" [label]=" 'Select'" ngDefaultControl>
</app-autocomplete>
and component.ts:
getFilterOptions(options, controlName) {
this.myForm.get(controlName).reset(options);
}