迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > Angular >

Angular 中按照对象属性过滤

作者:迹忆客 最近更新:2023/03/23 浏览次数:

网页中的过滤器功能允许用户快速缩小搜索范围,例如在您想要评估某个项目是否在一长串项目中的情况下。 此外,我们可以在要过滤列表的地方使用过滤器功能,例如汽车列表。

要按属性过滤对象,您可以按字符串、数字等过滤列表。在本文中,我们现在将研究在网页内执行过滤的各种方法。


按 Angular 中的任何对象属性过滤

在此示例中,我们想要创建一个允许我们使用任何条件(即字符串和数字)进行过滤的 Web 应用程序。 所以我们创建一个新的项目文件夹,然后导航到 index.html 文件来编写代码。

代码片段- index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example Filter</title>
  <script src="//code.angularjs.org/snapshot/angular.min.js"></script>
</head>
<body ng-app="">
  <div ng-init="friends = [{name:'John', phone:'555-1276'},
                         {name:'Mary', phone:'800-BIG-MARY'},
                         {name:'Mike', phone:'555-4321'},
                         {name:'Adam', phone:'555-5678'},
                         {name:'Julie', phone:'555-8765'},
                         {name:'Juliette', phone:'555-5678'}]"></div>
<label>Search: <input ng-model="searchText"></label>
<table id="searchTextResults">
  <tr><th>Name</th><th>Phone</th></tr>
  <tr ng-repeat="friend in friends | filter:searchText">
    <td>{{friend.name}}</td>
    <td>{{friend.phone}}</td>
  </tr>
</table>
<hr>
</table>
</body>
</html>

它将对象数组组织成一个表,然后我们还提供了一个输入栏,我们将使用它来过滤对象。 然后我们必须创建一个新文件,将其命名为 filter.js; 这是我们为应用程序添加功能的地方。

代码片段- filter.js

var expectFriendNames = function(expectedNames, key) {
    element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
      arr.forEach(function(wd, i) {
        expect(wd.getText()).toMatch(expectedNames[i]);
      });
    });
  };

  it('should search across all fields when filtering with a string', function() {
    var searchText = element(by.model('searchText'));
    searchText.clear();
    searchText.sendKeys('m');
    expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');

    searchText.clear();
    searchText.sendKeys('76');
    expectFriendNames(['John', 'Julie'], 'friend');
  });

所以我们为搜索输入创建了一个函数,然后我们在 searchText 变量中调用模型。 请参阅下面的输出:

按 Angular 中的任何对象属性过滤


按 Angular 中的特定对象属性过滤

这一次,我们想创建一个应用程序,我们可以在其中按特定属性进行过滤,我们将按字符串进行过滤,字符串仅有效,我们按数字进行过滤,仅数字有效,然后我们还将有搜索过滤器 在任何地方我们都可以通过字符串和数字进行搜索。

我们将创建一个新的角度项目并导航到 index.html 文件以添加将创建页面结构的代码; 它将包含一个仅按数字和仅按字符串搜索任何内容的搜索栏。

代码片段- index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-filter-filter-production</title>
  <script src="//code.angularjs.org/snapshot/angular.min.js"></script>
</head>
<body ng-app="">
  <div ng-init="friends = [{name:'John', phone:'555-1276'},
                         {name:'Mary', phone:'555-2578'},
                         {name:'Mike', phone:'555-4321'},
                         {name:'Adam', phone:'555-5678'},
                         {name:'Julie', phone:'555-8765'},
                         {name:'Juliette', phone:'555-5678'}]">
    </div>
<hr>
<label>Any: <input ng-model="search.$"></label> <br>
<label>Name only <input ng-model="search.name"></label><br>
<label>Phone only <input ng-model="search.phone"></label><br>
<table id="searchObjResults">
  <tr><th>Name</th><th>Phone</th></tr>
  <tr ng-repeat="friendObj in friends | filter:search:strict">
    <td>{{friendObj.name}}</td>
    <td>{{friendObj.phone}}</td>
  </tr>
</table>
</body>
</html>

此时,我们应该看到具有上面定义的结构的网页。 现在是为应用程序设计功能。

我们将创建一个新文件,将其命名为 filter.js,然后我们将输入以下代码:

代码片段- filter.js

var expectFriendNames = function(expectedNames, key) {

  it('should search in specific fields when filtering with a predicate object', function() {
    var searchAny = element(by.model('search.$'));
    searchAny.clear();
    searchAny.sendKeys('i');
    expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  });
  it('should use a equal comparison when comparator is true', function() {
    var searchName = element(by.model('search.name'));
    var strict = element(by.model('strict'));
    searchName.clear();
    searchName.sendKeys('Julie');
    strict.click();
    expectFriendNames(['Julie'], 'friendObj');
  });

通过 searchAny 变量,我们表明用户可以使用字符串或数字进行过滤。

在我们声明了 searchName 变量之后,我们还声明了一个严格的变量,这样我们在数字输入字段中使用字符串过滤的地方就不会显示任何数据。 当我们尝试使用字符串输入字段中的数字进行过滤时,也会发生同样的情况。

请参阅下面的输出:

按 Angular 中的特定对象属性过滤


在 Angular 中使用管道按对象属性过滤

管道非常适合运行两个命令或进程,这非常适合我们在这里所做的事情。 例如,我们要过滤,这是一个进程,让它返回过滤的结果,这是第二个进程。

因此,我们想要创建一个新的角度项目,然后我们想要创建一个新文件来保存我们要过滤的项目的详细信息。 将文件命名为 cars.ts 并输入以下代码:

代码片段- cars.ts

export const CARS = [
    {
      brand: 'Audi',
      model: 'A4',
      year: 2018
    }, {
      brand: 'Audi',
      model: 'A5 Sportback',
      year: 2021
    }, {
      brand: 'BMW',
      model: '3 Series',
      year: 2015
    }, {
      brand: 'BMW',
      model: '4 Series',
      year: 2017
    }, {
      brand: 'Mercedes-Benz',
      model: 'C Klasse',
      year: 2016
    }
  ];

接下来,我们要创建一个文件结构,将 cars.ts 中的数据组织到一个表中,包括过滤器的输入字段。 我们将在 app.component.html 文件中输入代码:

代码片段- app.component.html

<div class="container">
  <h2 class="py-4">Cars</h2>
  <div class="form-group mb-4">
    <input class="form-control" type="text" [(ngModel)]="searchText" placeholder="Search">
  </div>
  <table class="table" *ngIf="(cars | filter: searchText).length > 0; else noResults">
    <colgroup>
      <col width="5%">
      <col width="*">
      <col width="35%">
      <col width="15%">
    </colgroup>
    <thead>
      <tr>
        <th scope="col">#</th>
        <th scope="col">Brand</th>
        <th scope="col">Model</th>
        <th scope="col">Year</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let car of cars | filter: searchText; let i = index">
        <th scope="row">{{i + 1}}</th>
        <td>{{car.brand}}</td>
        <td>{{car.model}}</td>
        <td>{{car.year}}</td>
      </tr>
    </tbody>
  </table>
  <ng-template #noResults>
    <p>No results found for "{{searchText}}".</p>
  </ng-template>
</div>

现在我们要处理应用程序的功能; 我们将创建一个新文件,将其命名为 filter.pipe.ts 并包含以下代码:

代码片段- filter.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {
  transform(items: any[], searchText: string): any[] {
    if (!items) return [];
    if (!searchText) return items;

    return items.filter(item => {
      return Object.keys(item).some(key => {
        return String(item[key]).toLowerCase().includes(searchText.toLowerCase());
      });
    });
   }
}

我们从 Angular 核心导入了 PipePipeTransform,因此当我们过滤项目时,它会转换数据并返回过滤后的结果。 接下来,我们需要访问 app.component.ts 文件来添加一些代码来增加功能。

代码片段- app.component.ts

import { Component } from '@angular/core';
import { CARS } from './cars';

interface Car {
  brand: string;
  model: string;
  year: number;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'filthree';
  cars: Car[] = CARS;
  searchText: string;
}

我们声明了 cars.ts 数组中项目的数据类型。 最后,我们必须将所需的模块导入到 app.module.ts 文件中。

代码片段- app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { FilterPipe } from './filter.pipe';

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, FilterPipe ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

完成所有步骤后,我们将看到以下输出:

在 Angular 中使用管道按对象属性过滤

因此,使用 Angular 对项目进行排序是一项让我们网站上的用户方便的功能,因为它有助于快速搜索想要的东西。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便