I need your help. I have a small piece of code in which I have a select
i option
. With their help, I iterate through the elements and select the one I need. The point is that I need to do a search inside this select
. That is, I can both select an item from the list and start typing, looking for the item I need and the items are shown to me. Please help to do this? Thank you very much
<mat-select formControlName="targetListValue">
<input>
<mat-option [selected]="true" [value]="null"></mat-option>
<mat-option *ngFor="let targetItem of targetListOptions" [value]="targetItem.id">
{{ targetItem.name }}
</mat-option>
</mat-select>
CodePudding user response:
You can use the idea of 'autocomplete' control.
angular material provides an autoComplete component that contains a select with input:
The autocomplete is a normal text input enhanced by a panel of suggested options.
HTML CODE:
<form >
<mat-form-field appearance="fill">
<mat-label>Number</mat-label>
<input type="text"
placeholder="Pick one"
aria-label="Number"
matInput
[formControl]="myControl"
[matAutocomplete]="auto">
<mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{option}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
TS CODE:
import {Component, OnInit} from '@angular/core';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';
/**
* @title Highlight the first autocomplete option
*/
@Component({
selector: 'autocomplete-auto-active-first-option-example',
templateUrl: 'autocomplete-auto-active-first-option-example.html',
styleUrls: ['autocomplete-auto-active-first-option-example.css'],
})
export class AutocompleteAutoActiveFirstOptionExample implements OnInit {
myControl = new FormControl('');
options: string[] = ['One', 'Two', 'Three'];
filteredOptions: Observable<string[]>;
ngOnInit() {
this.filteredOptions = this.myControl.valueChanges.pipe(
startWith(''),
map(value => this._filter(value || '')),
);
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.options.filter(option => option.toLowerCase().includes(filterValue));
}
}
CSS:
.example-form {
min-width: 150px;
max-width: 500px;
width: 100%;
}
.example-full-width {
width: 100%;
}