【发布时间】:2018-09-02 06:19:24
【问题描述】:
我在我的 Angular 应用程序中使用管道根据用户提供的搜索输入过滤选项值。此过滤器用于表单的字段级别,该表单使用 ngFor 循环并基于 json 响应动态生成。
我可以使用管道概念来过滤独立单个输入的值,但是当我使用 Ngfor Loop 多次使用它时,就像下面的代码一样,它不能完美地工作。
// formdata is coming as of json response from a http request
<div *ngFor="let input1 of formdata.formfields">
<mat-select placeholder="Select something" [formControlName]="input1.field_name">
<ngx-mat-select-search [(ngModel)]="searchText" [ngModelOptions]="{standalone: true}" placeholder="Select {{input1.title}}"></ngx-mat-select-search>
// here I am using 'fitleroptions' pipe after ngFor and passing searchText ngmodel input binding
<mat-option *ngFor="let opt_value of input1.enumNameGroups | filteroptions : searchText; let i = index" value={{input1.value}}>{{opt_value}}</mat-option>
</mat-select>
// other input types like file, text etc....
</div>
这给了我这样的输出。
现在的问题是,分配给 ngmodel 的 searchText 只能使用一次,因为它仅限于一个输入,如果我这样做,它也会影响其他输入。
如何传递 [(ngmodel)] ="some_variable" 然后将其分配给 filteroptions : "some_variable" 以便它们仅限于一个选择输入???
所以问题也可以表达为如何传递动态 ngmodel 名称并将该名称分配给管道参数?
这是我正在使用的 filteroptions 管道。
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filteroptions'
})
export class FilterOptionsPipe implements PipeTransform {
transform(items: any[], searchText: string): any[] {
if(!items) return [];
if(!searchText) return items;
searchText = searchText.toLowerCase();
return items.filter( it => {
console.log("got item array here",items);
return it.toLowerCase().includes(searchText);
});
}
}
【问题讨论】:
-
如果您咨询管道,也许您应该发布该管道的代码...
-
嘿,谢谢你的提醒。在我自己提出的问题中,我真的错过了这段代码。
标签: angular typescript angular-pipe angular2-ngmodel