简体   繁体   中英

How can I show an element depending on selected option in a dropdown

I have created 3 cards in Angular from an object array. one of the properties of the objects is "price". if I wanted to include a select element, with 2 options, one of them saying "lower than 2000" and the other saying "bigger that 2000",

What would be the best way to show only the elements with a higher price of ..for example, 2000?

this is the HTML I've done:

<div class="mat-card-wrapper">
    <mat-card *ngFor="let person of dataArray; let i= index">
        <mat-card-title-group>
            <mat-card-subtitle>
                <span class="boldy">BookingId:</span>
                <span>
                    {{person.bookingId}}
                </span>
                <span class="boldy"> Cliente:</span>
                <span>
                    {{person.locationId.tutenUser.firstName +" "+
                    person.locationId.tutenUser.lastName}}
                </span>
                <span class="boldy">Fecha de Creación</span>
                <span>{{person.bookingTime}}</span>
                <span class="boldy">Dirección</span>
                <span>{{person.locationId.streetAddress}}</span>
                <span class="boldy">Precio</span>
                <span>{{person.bookingPrice}}</span>
            </mat-card-subtitle>
        </mat-card-title-group>
    </mat-card>
</div>

This generates 3 cards, I can't come out with the right way of adding a simple <selec> method that allow me to show only the elements with a price bigger than 2000 and the ones lower than 2000.

I know this is a very basic question but I'm stuck, can anyone help me with this?

Thanks.

You could add a pipe to your ngFor which would filter your data depending on what you selected (<2000 or >2000).

<mat-card *ngFor="let person of dataArray | myfilterPipe:myCondition">

Your pipe would look like something like that:

 import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'myfilterPipe',
})
export class MyFilterPipe implements PipeTransform {
    transform(items: any[], filter: condition): any {
        if (!items || !filter) {
            return items;
        }
        if(condition === over2000) {
           return items.filter(item => item.price > 2000);
        }
        if(condition === under2000) {
           return items.filter(item => item.price < 2000);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM