使过滤管成角度6

时间:2018-05-21 14:40:52

标签: angular typescript

我正在尝试使用angular6制作过滤器管道。到目前为止我得到了这个:

search.component.html:

<input class="form-control" [(ngModel)]="searchService.query.title" name="title">

search.component.ts:

import { Component, OnInit } from '@angular/core';
import { SearchDataService } from './search-data.service';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent {

  constructor(public searchService: SearchDataService) {
  }
}

搜索data.service.ts:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class SearchDataService {
  public query = {};
  constructor() { }
}

list.component.html:

<app-search></app-search>
<div>{{ searchService.query | json }}</div>
<div *ngIf="estates">
  <div *ngFor="let estate of estates | filter: searchService.query">
    <app-estates-estate [estate]="estate" [appClassSwitch]="'estate-details-list'"></app-estates-estate>
  </div>
</div>

如果我将所有这些更改为只添加一个按钮来应用过滤器(将输入值分配给服务模型),它就能很好地工作。但是,如果我按照它在这里显示的方式执行它,它不会刷新应用过滤器的列表。我记得在angularjs中有类似$ rootScope。$ digest所以我试图搜索类似的东西,我得到了ApplicationRef和ChangeDetectorRef,但这些都没有解决我的情况。

所以问题是我如何强制执行过滤器应用程序,以便它影响屏幕上显示的列表?

由于

1 个答案:

答案 0 :(得分:0)

Angular 2+没有像angularjs那样的默认过滤器。您应该创建自己的过滤器(角度为2+的管道)。请参阅以下代码段

...
@pipe({
   name: "myCustomFilter",
   pure: false
})
export class MyCustomFilter implements PipeTransform {
   transform(input) {
      // Custom Logic 
      return output
    }
 }

只有当任何输入发生变化时,Angular才会执行纯管道...默认情况下,所有管道都是纯粹的......你应该把它标记为假......但是这会带来性能成本......请采取措施关心

...
@NgModule({
  imports: [CommonModule],
  declaration: [MyCustomFilter]
})
export class SomeModule {}

然后在模板中使用如下

<div *ngFor="let item of items | myCustomFilter: 'searchQuery'"> 
   {{item.name}}
</div>

有关管道的更多信息,请验证Angular.io

您可以参考此repo,它有很多可重复使用的管道angular-pipes

相关问题