[英]Filter and search unordered list Angular2
我正在尋找一種使用角度輸入字段過濾無序列表的方法。
我有一個組件,該組件使用*ngFor
指令在頁面加載時使用從JSON文件獲取的數據構建無序列表,該組件通過使用服務來獲取實際數據。 這是有問題的組件的代碼:
operation-catalogue.component.ts
:
import { Component, OnInit, Input } from '@angular/core';
import { OperationService } from "./operation.service";
@Component({
selector: 'operation-catalogue-component',
templateUrl: './operation-catalogue.component.html',
styleUrls: ['./operation-catalogue.component.css'],
})
export class OperationCatalogueComponent implements OnInit {
operationCatalogue = [];
constructor(private operationService: OperationService) { }
ngOnInit() {
//Get the items to put in the list...
this.operationCatalogue = this.operationService.getOperations();
}
}
operation-catalogue.component.html
:
<div id="search-box-div">
<div id="search-field" class="top-div">
<input #input type="text" placeholder="Filter">
</div>
</div>
<ul>
<!-- generate list, name only -->
<li *ngFor="let operation of operationCatalogue">
<label>{{operation.name}}</label>
</li>
</ul>
我故意省略了該服務,因為它可以按預期工作,並且在本示例中不需要。
我想做的是能夠過濾使用html input
元素生成的列表。
我試圖查看過去關於堆棧溢出的問題,但它們似乎都已過時,並使用了Angular2不再支持的方法。
我如何用現代方法實現這一目標?
為此,您將需要使用管道 。 這是一個示例,因為它相當長,所以我在Github上創建了要點。
操作catalogue.component.ts:
import { Component, OnInit, Input } from '@angular/core';
import { OperationService } from "./operation.service";
@Component({
selector: 'operation-catalogue-component',
templateUrl: './operation-catalogue.component.html',
styleUrls: ['./operation-catalogue.component.css'],
})
export class OperationCatalogueComponent implements OnInit {
operationCatalogue = [];
objectsFilter = {name: ''};
constructor(private operationService: OperationService) { }
ngOnInit() {
//Get the items to put in the list...
this.operationCatalogue = this.operationService.getOperations();
}
}
操作catalogue.component.html:
<div id="search-box-div">
<div id="search-field" class="top-div">
<input #input type="text" placeholder="Filter" [(ngModel)]="objectsFilter.name">
</div>
</div>
<ul>
<!-- generate list, name only -->
<li *ngFor="let operation of operationCatalogue | filterBy: {name: objectsFilter.name};">
<label>{{operation.name}}</label>
</li>
</ul>
Plunker示例: https ://embed.plnkr.co/xbW6nbkQZfwudOAnrEXl/
您可以使用Angular2 +的indexOf功能,
<li *ngIf="searchElement === '' || (label | lowercase).indexOf(searchElement | lowercase) != -1" >
這將工作而無需任何額外的管道。 如果找到匹配的文本,indexOf將返回任何數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.