我正在尝试使用带角度的ionic 4 ion-searchbar ui组件。我可以使用以下组件过滤数据,但无法将过滤器还原为原始数据 我的组件看起来像这样:
...
export class RepertorioPage implements OnInit {
data: any;
filtredData: any;
constructor(private newsService: NewsService, private router: Router) { }
ngOnInit() {
this.newsService.getData('everything?q=bitcoin&from=2018-12-25&sortBy=publishedAt')
.subscribe(data => {
this.data = data
this.filtredData = data
})
}
...
getFiltredRepertorio(ev: any){
let serVal = ev.target.value;
if(serVal && serVal.trim() != ''){
this.filtredData.articles = this.data.articles.filter((a) => {
return (a.title.toLowerCase().indexOf(serVal.toLowerCase()) > -1);
})
}
}
}
和我的html一样:
...
<ion-content>
<!-- List of Text Items -->
<ion-searchbar showCancelButton cancelButtonText="Custom Cancel" (ionChange) = getFiltredRepertorio($event) id="searchText"></ion-searchbar>
<ion-list>
<ion-item (click)="getRepertorio(article)" *ngFor="let article of filtredData?.articles">
<ion-label>{{article.title}}</ion-label>
</ion-item>
</ion-list>
</ion-content>
出了什么问题?我该如何解决?
答案 0 :(得分:1)
尝试克隆数据,而不要指向其引用。 例如,使用具有clone或cloneDeep
的lodash(从'lodash'导入*作为_)this.data = _.clone(data)
this.filtredData = data
答案 1 :(得分:1)
编辑:
如果formcontrol引起了麻烦,我们可以使用ionChange
做同样的事情:
<ion-searchbar ... (ionChange)="doFilter($event)"></ion-searchbar>
和doFilter
看起来像这样:
doFilter(val) {
this.filteredData = this.data.map(data => data.articles).map(options =>
options.filter(option =>
option.title.toLowerCase().indexOf(val.value.toLowerCase()) > -1)
)
}
原始:
我将数据保留为Observable并使用异步管道和formcontrol:
myControl = new FormControl();
filteredData: Observable<any[]>;
data: Observable<any[]>;
// ...
ngOnInit() {
this.data = this.newsService.getData('...')
this.filteredData = this.myControl.valueChanges
.switchMap(value => this.filter(value))
}
filter(value: string): Observable<any[]> {
return this.data.map(data => data.articles)
.map(options => options
.filter(option => option.title.toLowerCase().indexOf(value.toLowerCase()) > -1)
)
}
然后在模板中设置异步管道并标记formcontrol,我们将监听并过滤到其中的更改:
<ion-content>
<ion-searchbar ... [formControl]="myControl"></ion-searchbar>
<ion-list>
<ion-item ... *ngFor="let article of filteredData | async">
<ion-label>{{article.title}}</ion-label>
</ion-item>
</ion-list>
</ion-content>
这是 DEMO
请注意,请勿使用any
,输入数据:)