html 使用Angular 滤波数据

ee7vknir  于 2022-11-27  发布在  Angular
关注(0)|答案(1)|浏览(110)

我是一个Angular 的新手,正在尝试过滤数据。我已经创建了一个网页,显示了一个酒店列表,但我想根据他们的星星来过滤它们。我甚至不知道如何尝试这个。任何帮助都将不胜感激!
酒店.组件.ts:

import { Component } from '@angular/core';
import { WebService } from './web.service';


@Component({
  selector: 'hotels',
  templateUrl: './hotels.component.html',
  styleUrls: ['./hotels.component.css']
})
export class HotelsComponent {

    hotel_list: any;
    page: number = 1;

    constructor(public webService: WebService) { }

    ngOnInit() {
        if (sessionStorage['page']) {
          this.page = Number(sessionStorage['page'])
        }
        this.hotel_list = this.webService.getHotels(this.page);
    }

Web服务.ts:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable()
export class WebService {

    private hotelID: any;

    constructor(private http: HttpClient) { }

    getHotels(page: number) { 
        return this.http.get('http://localhost:5000/api/v1.0/hotels?pn=' + page);

    }

hotels.components.html:

<div class="container">
    <div class="row">
        <div class="col-sm-12">
            <div *ngFor = "let hotel of hotel_list | async">
                <div class="card text-white bg-primary mb-3" 
                     style ="cursor : pointer"
                     [routerLink]="['/hotels', hotel._id]">
                    <div class="card-header">
                        {{ hotel.hotel }}
                    </div>
                    <div class="card-body">
                        This hotel is based in
                        {{ hotel.city }}
                    </div>
                    <div class="card-footer">
                        {{ hotel.rating }}
                        stars
                    </div>
                </div>
            </div>
wfsdck30

wfsdck301#

假设您需要在获取旅馆后在客户端筛选旅馆,也就是说,只返回page = 1的旅馆。
在酒店中。componenent.ts:

filtered_hotels_list: any = []; //empty array
//......
    ngOnInit() {
        if (sessionStorage['page']) {
          this.page = Number(sessionStorage['page'])
        }
        this.webService.getHotels(this.page).subscribe(data => { 
                this.hotel_list = data
                this.filter();
        });
        
}
filter(rating:number = -1) { // rating = -1 shows all
     if(rating > -1) {
         this.filtered_hotels_list = this.hotel_list.filter(o => o.rating == rating)
     } else this.filtered_hotels_list = this.hotel_list
 
}

在hotels.components.html中找到:

<div *ngFor = "let hotel of filtered_hotel_list">

并实现您的UI以添加一个过滤器按钮,该按钮调用filter(5)函数。

相关问题