我在 Web 开发方面有一些经验,但对 Angular 还很陌生。我正在尝试创建一个简单的过滤器来根据文本输入过滤表的一列。我遇到的问题是,当您在文本输入中输入单个字母时,所有结果都会被过滤掉。
AnimalsComponent.ts
import { ApiService } from '../api.service';
import { AnimalFilterPipe } from '../animal-filter.pipe'
@Component({
selector: 'app-animals',
templateUrl: './animals.component.html',
styleUrls: ['./animals.component.css'],
providers: [AnimalFilterPipe]
})
export class AnimalsComponent implements OnInit {
animals = [];
constructor(private apiService: ApiService) { }
ngOnInit() {
this.apiService.getA().subscribe((data: any[])=>{
console.log(data);
this.animals = data;
})
}
}
动物过滤管
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'animalFilter'
})
export class AnimalFilterPipe implements PipeTransform {
transform(animals: any, term: string): any {
//check if the search term is defined
if(!animals || !term) return animals;
//return updated animals array
animals.filter(function(animal){
return animal.Animal.toLowerCase().includes(term.toLowerCase());
})
}
}
动物.html
<div style="padding: 13px;">
<form id = "animalFilter">
<label>Filter by Animal:</label>
<input type="text" [(ngModel)]= "term" [ngModelOptions]="{standalone: true}"/>
</form>
<table>
<tr>
<th>Hemisphere</th>
<th>Type</th>
<th>Animal</th>
<th>Seasonality</th>
<th>Location</th>
<th>Time</th>
<th>Price</th>
</tr>
<td align="center">TBD</td>
</ng-template>
</tr>
</table>
</div>
如果有人可以帮助我并给我一些关于我需要更改的内容以及如何更好地前进的建议,以便我可以创建更多的过滤管道和更多的自定义管道。
互换的青春
相关分类