我正在尝试使用自定义管道*ngFor
使用带有 ngModel 的输入字段过滤我的循环。使用我的其他自定义管道(sortBy),它工作得非常好。但是,过滤器管道似乎使它没有出现任何数据。我还在学习这个,我尝试了一些变化无济于事:
-filter: term
-filter: {{term}}
-filter: 'term'
-filter" {{'term'}}
所以我认为问题可能出在代码的其他地方。如果有人可以提供帮助,我将不胜感激。
这是我的代码:
HTML 组件
<div style="text-align:center">
<h1>
Welcome to {{title}}!!
</h1>
</div>
<h2>Please choose your favorite song: </h2>
<form id="filter">
<label>Filter people by name:</label>
<input type="text" name="term" [(ngModel)]="term" />
</form>
<table class="table">
<thead>
<tr>
<th>Title</th>
<th>Artist</th>
<th>Likes</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let song of songs | filter:term| sortBy: 'likes'; let i = index">
<td>{{song.title}}</td>
<td>{{song.artist}}</td>
<td>{{song.likes}}
<i class="fa fa-heart-o" aria-hidden="true" *ngIf="song.likes < 1"></i>
<i class="fa fa-heart" aria-hidden="true" *ngIf="song.likes >= 1"></i>
<i class="fa fa-plus" aria-hidden="true" (click)="addLike(i)" ></i>
<i class="fa fa-minus" aria-hidden="true" (click)="removeLike(i)" ></i>
</td>
</tr>
</tbody>
</table>
管道
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter',
pure: false
})
export class FilterPipe implements PipeTransform {
transform(items: any[], args: any[]): any {
return items.filter(item => item.id.indexOf(args[0]) !== -1);
}
}
模块
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { SortByPipe } from './sort-by.pipe';
import { FilterPipe } from './filter.pipe';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { Pipe, PipeTransform } from '@angular/core';
@NgModule({
declarations: [
AppComponent,
SortByPipe,
FilterPipe
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
JS 组件
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
title = 'Oxcord';
songs = [
{title: "Song", artist: "Artist", likes: 1},
{title: "Chanson", artist: "Artiste", likes: 3},
{title: "ABC", artist: "OneTwoThree", likes: 2},
{title: "Trash", artist: "Meek Mill", likes: 0}
];
addLike(input){
this.songs[input].likes +=1;
}
removeLike(input){
this.songs[input].likes -=1;
}
args="Me";
}