[Angular Material] 搜尋式下拉選單範例
範例
https://stackblitz.com/edit/filter-select
來源
https://forum.angular.tw/t/topic/1722/4
HTML
<mat-card>
<p mat-card-title>Angular Material Select With Filter</p>
<mat-divider></mat-divider>
<mat-card-content>
<br><br>
<mat-form-field style="width: 100%;">
<mat-label>Pick a language</mat-label>
<mat-select [formControl]="control">
<mat-option disabled>
<input type="text" matInput [formControl]="filter" placeholder="Filter...">
</mat-option>
<mat-option value="" *ngIf="control.value && !filter.value">
<mat-icon>replay</mat-icon> Reset Input
</mat-option>
<ng-container *ngIf="filtedOptions | async as filted">
<mat-option disabled *ngIf="filted.length == 0">No Option Found</mat-option>
<mat-option *ngFor="let opt of options"
[value]="opt.value"
[ngStyle]="getOptionStyle(opt, filted)">{{ opt.label }}</mat-option>
</ng-container>
</mat-select>
<mat-error>this field is required</mat-error>
</mat-form-field>
<br>
<p>Selected Value : {{ control.value }}</p>
<br>
</mat-card-content>
</mat-card>
TS檔
export class AppComponent {
control: FormControl = new FormControl('', [Validators.required])
filter: FormControl = new FormControl('');
filtedOptions: Observable<Array<Option>>;
options: Array<Option> = [
{ label: 'Traditional Chinese', value: 'zh-TW' },
{ label: 'Japanese', value: 'jp' },
{ label: 'English', value: 'en' },
{ label: 'Simplified Chinese', value: 'zh-CN' },
{ label: 'Spanish', value: 'es' },
{ label: 'Portuguese', value: 'pt' },
{ label: 'Korean', value: 'zh-kor' },
];
constructor() {}
ngOnInit() {
this.filtedOptions = this.filter.valueChanges.pipe(
debounceTime(50),
startWith(''),
map(target => target.toLowerCase()),
tap(target => console.log(target)),
map(target => this.options.filter(opt => opt.label.toLowerCase().includes( target )))
);
}
getOptionStyle(opt: Option, filted: Array<Option>): {[key: string]: any} {
const style: {[key: string]: any} = {};
style.display = filted.indexOf(opt) < 0 ? 'none' : '';
return style;
}
}
interface Option {
label: string;
value: any;
}
留言
張貼留言