用angular7写一个模糊查询
时间: 2023-05-18 09:02:54 浏览: 182
可以使用 Angular Material 中的 MatAutocomplete 组件来实现模糊查询。首先,需要在组件中引入 MatAutocomplete 和 FormControl:
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatAutocomplete } from '@angular/material';
@Component({
selector: 'app-autocomplete',
templateUrl: './autocomplete.component.html',
styleUrls: ['./autocomplete.component.css']
})
export class AutocompleteComponent {
searchControl = new FormControl();
options = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
filteredOptions: string[];
filterOptions() {
const filterValue = this.searchControl.value.toLowerCase();
this.filteredOptions = this.options.filter(option => option.toLowerCase().includes(filterValue));
}
}
然后,在模板中使用 MatAutocomplete 组件:
<mat-form-field>
<input type="text" placeholder="Search" matInput [formControl]="searchControl" (input)="filterOptions()">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option of filteredOptions" [value]="option">
{{ option }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
这样就可以实现一个简单的模糊查询功能了。
阅读全文