搜索栏,带有来自 Ionic 3 的 JSON 数据的过滤器



我想有一个搜索栏,根据书名过滤结果,我尝试这样做,但它不起作用。当我在寻找东西时,什么都没有发生,没有错误,所以我错了,但我不知道是什么,我是打字稿的新手,我寻求帮助。提前致谢

这是我page.html

<ion-content padding>
<ion-searchbar placeholder="Filter Items" (ionInput)="getItems($event)"></ion-searchbar>
<ion-grid>
<ion-row>
<ion-col *ngFor="let item of items">
<ion-card-header><h1>{{item.title}}</h1></ion-card-header>
<ion-card-header><h3>Autore:{{item.author}}</h3></ion-card-header>
<div id="immagine">
<img src="../assets/{{item.imageLink}}">
</div>
</ion-col>
</ion-row>
</ion-grid>   
</ion-content> 

这是我page.ts文件:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable'
import 'rxjs/add/operator/map';
@IonicPage()
@Component({
selector: 'page-tab2',
templateUrl: 'tab2.html',
})
export class Tab2Page {
items:any;

constructor(public navCtrl: NavController, public navParams: NavParams, public http: HttpClient) {
this.loadData();
}
loadData(){
let data:Observable<any>;
data = this.http.get("assets/books.json");
data.subscribe(result => {
this.items = result;
this.initiazileItems();
})
}
initiazileItems(){
this.items= this.items;
}
getItems(ev:any){
this.initiazileItems();
let val = ev.target.value;
}
filterItems(ev: any) {
this.loadData();
let val = ev.target.value;
if (val && val.trim() != '') {
this.items = this.items.filter((item) => {
return (item.title.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
}
}
}

我的 JSON 示例:

{
"author": "Hans Christian Andersen",
"country": "Denmark",
"imageLink": "images/fairy-tales.jpg",
"language": "Danish",
"link": "https://en.wikipedia.org/wiki/Fairy_Tales_Told_for_Children._First_Collection.n",
"pages": 784,
"title": "Fairy tales",
"year": 1836
},

将搜索栏更改为以下内容

<ion-searchbar placeholder="Filter Items" [(ngModel)]="searchTerm" (ionInput)="filterItems()"></ion-searchbar>
<ion-grid>
<ion-row>
<ion-col *ngFor="let item of filterItems">
<ion-card-header><h1>{{item.title}}</h1></ion-card-header>
<ion-card-header><h3>Autore:{{item.author}}</h3></ion-card-header>
<div id="immagine">
<img src="../assets/{{item.imageLink}}">
</div>
</ion-col>
</ion-row>
</ion-grid>   

然后在您的 ts 文件中添加以下内容:

searchTerm: string ;
filterItems:any;
loadData(){
let data:Observable<any>;
data = this.http.get("assets/books.json");
data.subscribe(result => {
this.items = result;
this.filterItems= this.items;
})
filterItems(){
this.filterItems = this.items.filter(item =>  item.title.toLowerCase().indexOf(this.searchTerm.toLowerCase()) > -1;
)
}

相关内容

  • 没有找到相关文章

最新更新