【发布时间】:2020-07-26 00:00:12
【问题描述】:
我在 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());
})
}
}
Animals.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>
<tr *ngFor="let animal of animals | animalFilter:term">
<td align="center">{{ animal.Hemisphere }}</td>
<td align="center">{{ animal.Type }}</td>
<td align="center" >{{ animal.Animal }}</td>
<td align="center">{{ animal.Seasonality }}</td>
<td align="center">{{ animal.Location }}</td>
<td align="center">{{ animal.Time }}</td>
<td align="center" *ngIf="animal.Price; else noPrice">{{ animal.Price }} Bells</td>
<ng-template #noPrice>
<td align="center">TBD</td>
</ng-template>
</tr>
</table>
</div>
如果有人可以帮助我,并就我需要更改的内容以及如何更好地向前推进,以便我可以创建更多过滤器管道和更多自定义管道,给我一些建议。
【问题讨论】:
-
您需要对此进行代码审查吗?
-
所以你需要在输入多个字母时开始过滤?请描述你想要得到的行为
-
@GuerricP 所以我期望看到的行为是任何长度的字符串都应该减少表中显示的结果。例如,我有 10 只动物,其中 6 只包含字母“A”,所以当我输入“A”时,我希望看到这四种动物。相反,即使输入一个字母,所有结果都会被过滤掉,表格是空的。
-
@Lemmy 基本上是的。但是,我想从根本上知道为什么我的代码没有按预期工作。
标签: javascript html angular web