在Mat-Select中实现搜索功能可以通过以下步骤完成:
<mat-form-field>
<mat-select placeholder="选择项" [(ngModel)]="selectedItem" (selectionChange)="onSelectionChange($event)">
<mat-option *ngFor="let item of items" [value]="item">{{ item }}</mat-option>
</mat-select>
</mat-form-field>
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
items: string[] = ['选项1', '选项2', '选项3', '选项4'];
selectedItem: string;
onSelectionChange(event) {
console.log(this.selectedItem);
}
}
<mat-form-field>
<input matInput placeholder="搜索" [(ngModel)]="searchText">
</mat-form-field>
<mat-form-field>
<mat-select placeholder="选择项" [(ngModel)]="selectedItem" (selectionChange)="onSelectionChange($event)">
<mat-option *ngFor="let item of items | filter: searchText" [value]="item">{{ item }}</mat-option>
</mat-select>
</mat-form-field>
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(items: string[], searchText: string): string[] {
if (!searchText) {
return items;
}
searchText = searchText.toLowerCase();
return items.filter(item => item.toLowerCase().includes(searchText));
}
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { ExampleComponent } from './example.component';
import { FilterPipe } from './filter.pipe';
@NgModule({
declarations: [
AppComponent,
ExampleComponent,
FilterPipe
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
现在,当用户在输入框中输入搜索关键字时,下拉选择框中的选项将根据输入的内容进行动态过滤。用户选择的项将存储在selectedItem变量中,并在onSelectionChange方法中进行处理。
腾讯云相关产品和产品介绍链接地址:
Elastic 实战工作坊
Elastic 实战工作坊
云+社区沙龙online第5期[架构演进]
企业创新在线学堂
云+社区技术沙龙[第17期]
企业创新在线学堂
腾讯位置服务技术沙龙
领取专属 10元无门槛券
手把手带您无忧上云