我遇到的问题是加载页面并进行API调用时,ngfor循环无法显示所有值,但是当我在搜索框中键入内容进行过滤时,它可以正常工作,我想要什么要做的是在页面最初加载时未应用搜索过滤器时返回所有值。
/*Filter Pipe*/
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter',
})
export class FilterPipe implements PipeTransform {
transform(value: string, filterString: string, propName: string): any {
if (value === null && value.length < 1 || filterString === '') {
return value;
/*This value isn't returning when fiter isn't applied on load*/
}
const resultArray = [];
for (const item of value) {
filterString = filterString.toLowerCase();
if (item[propName].toLowerCase().indexOf(filterString) >= 0) {
resultArray.push(item);
}
}
return resultArray;
}
}
/*Conponent*/
ngOnInit() {
this.api.getStopData().subscribe(
data => {
this.stations = data;
}
);
}
<div class="container">
<form class="form-inline md-form form-sm active-pink-2 mt-2">
<input class="form-control form-control-sm mr-3 w-75" name="search" [(ngModel)]="search" type="text"
placeholder="Search train stations" aria-label="Search">
<i class="fas fa-search" aria-hidden="true"></i>
</form>
<!-- Card -->
<div *ngFor="let station of stations?.results?.objStation | filter:search:'StationDesc'">
<mdb-card class="m-1">
<!--Card content-->
<mdb-card-body>
<!--Title-->
<mdb-card-title>
<h4>{{station.StationDesc}} Train Station</h4>
<hr/>
</mdb-card-title>
<img class="col-6 panel-realtime" src="assets/img/icon_view.png" (click)="getStation(station.StationCode); basicModal.show()"
mdbWavesEffect/>
<img class="col-6 panel-remove" src="assets/img/thumbnail_icon_map.png" (click)="getMaps(station.StationDesc); mapsModal.show()" mdbWavesEffect/>
</mdb-card-body>
</mdb-card>
</div>
</div>
答案 0 :(得分:4)
我假设您不是在初始化搜索变量,因为您上面没有提到。如果您没有在component.ts中初始化 search 变量,则页面加载。 搜索变量的值将为未定义而不是''
解决方案1:
export class Component implements OnInit{
search: string;
constructor() {
this.search = '';
}
ngOnInit() {
this.api.getStopData().subscribe(
data => {
this.stations = data;
}
);
}
}
解决方案2:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter',
})
export class FilterPipe implements PipeTransform {
transform(value: string, filterString: string, propName: string): any {
if (value === null && value.length < 1 || (filterString === '' || filterString === undefined)) {
return value;
/*This value isn't returning when fiter isn't applied on load*/
}
const resultArray = [];
for (const item of value) {
filterString = filterString.toLowerCase();
if (item[propName].toLowerCase().indexOf(filterString) >= 0) {
resultArray.push(item);
}
}
return resultArray;
}
}