在 Angular 中创建搜索过滤器

Muhammad Adil 2023年1月30日
  1. Angular 搜索过滤器
  2. 在 Angular 中创建搜索过滤器的步骤
  3. 自定义搜索过滤器的优势
在 Angular 中创建搜索过滤器

本文将演示如何使用 ng2-search-filter 包和 ngfor 循环指令在 Angular 项目中创建搜索过滤器来过滤收集的数据。

Angular 搜索过滤器

Angular 框架包含许多可以创建各种应用程序的功能。其中一项功能是能够使用管道,这是一种过滤器,可以在数据显示在屏幕上之前应用于数据。

Angular 搜索过滤器提供了一种声明性的方式来过滤进入或离开控制器范围的数据。过滤器可以应用于任何数据对象:字符串、数组、对象,甚至是原语。

过滤器从左到右执行,直到一个返回 true,或者所有过滤器都已执行但没有返回 true。在 Angular 中构建自定义搜索的最佳方法是使用 ng2-search-filter 包,而不是使用任何第三方库。

在 Angular 中创建搜索过滤器的步骤

本节将演示在 Angular 中创建搜索过滤器所需的步骤。

安装 Angular CLI

首先,安装用于开发 Angular 应用程序的 Angular CLI 工具。运行此命令以安装 Angular CLI。

npm install @angular/cli

安装 ng2-search-filter

第二步也是最重要的一步是安装 ng2-search-filter 包。

npm i ng2-search-filter

ng2-search-filter 为 Angular 应用程序提供搜索输入组件。它允许用户通过在输入框中键入来过滤项目列表。

该组件是高度可配置的,并支持许多不同的数据源。

导入模块

第三步是在 App Module 类中导入 FormsModuleNg2SearchPipeModule。因为如果你想为你的网站创建一个搜索表单,你需要导入这两个模块。

在你的 Angular 应用程序中编写以下代码。

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { Ng2SearchPipeModule } from 'ng2-search-filter';
import { AppComponent } from './app.component';
@NgModule({
    imports:      [ BrowserModule, FormsModule, Ng2SearchPipeModule ],
    declarations: [ AppComponent ],
    bootstrap:    [ AppComponent ]
})
export class AppModule { }

编写 TypeScript 和 HTML 代码

此步骤将决定你的搜索过滤器的外观。我们将编写 TypeScript 和 HTML 代码。

TypeScript 代码:

import { Component } from '@angular/core';
@Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: [ './app.component.css']
})
export class AppComponent {
    searchText: any;
    names = [
        { country: 'Adil'},
        { country: 'John'},
        { country: 'Jinku'},
        { country: 'Steve'},
        { country: 'Sam'},
        { country: 'Zeed'},
        { country: 'Abraham'},
        { country: 'Heldon'}
    ];
}

HTML 代码:

 <h1>Example of Angular Search Filter</h1>
<div class="container">
    <div class="search-name">
        <input class="form-control" type="text" name="search" [(ngModel)]="searchText" autocomplete="on" placeholder=" SEARCH  ">
    </div>
    <ul *ngFor="let name of names | filter:searchText">
        <li>
            <span>{{name.country}}</span>
        </li>
    </ul>
</div>

在这个例子中,我们编写了一些随机名称,并且在 ng2-search-filterng-for 循环的帮助下,我们能够通过搜索过滤数据。

自定义搜索过滤器的优势

我们已经学习了在 Angular 中创建搜索过滤器的所有步骤。让我们看看借助 ng2-search-filter 包创建自定义搜索过滤器的好处。

  1. 使用方便,可根据应用需求定制。
  2. 它是一个 Angular 核心组件,提供了灵活性和准确性。
  3. 搜索过滤器可用于任何数据,而不仅仅是字符串。

点击这里查看以上所有步骤的演示。

作者: Muhammad Adil
Muhammad Adil avatar Muhammad Adil avatar

Muhammad Adil is a seasoned programmer and writer who has experience in various fields. He has been programming for over 5 years and have always loved the thrill of solving complex problems. He has skilled in PHP, Python, C++, Java, JavaScript, Ruby on Rails, AngularJS, ReactJS, HTML5 and CSS3. He enjoys putting his experience and knowledge into words.

Facebook