Yauhen
Yauhen

Reputation: 143

Angular filtering with dropdown

I have the following code:

HTML:

<select>
  <option *ngFor="let item of items">{{item}}</option>
</select>

Some Angular service:

items = [
{name: "item1", type: "type1"},
{name: "item2", type: "type2"},
{name: "item3", type: "type2"}

];

And some filtering function, which filters an array by type and returns new array.

I haven't got problems with filtering by button like:

<button type="button" (click)="Filter('type2')"></button>

But I can't do it using dropdown.

UPD: Incorrect explanation. Here live demo. Need to filter array with (change) event at select tag using brandName

Upvotes: 5

Views: 25674

Answers (2)

Kirill
Kirill

Reputation: 406

Set ngModel to get selected value and change event to update the list:

<select [(ngModel)]="selectedBrand" (change)="valueSelected()">
  <option *ngFor="let item of brandName">{{ item }}</option>
</select>

Then filtering items in the component when value has been changed:

public selectedBrand;
public valueSelected() {
    this.goods = this.goodsService.goods.filter(item => item.name === this.selectedBrand);
}

Demo

Upvotes: 5

mkHun
mkHun

Reputation: 5927

Try this

AppComponent.ts file

export class AppComponent{

    constructor(){}
    items = [
        {name: "item1", type: "type1"},
        {name: "item2", type: "type2"},
        {name: "item3", type: "type2"}
    ];

makeArr(e){
    console.log(e);
}

}

html

<select (change)='makeArr($event.target.value)'>
    <option *ngFor="let item of items">{{item.name}}</option>
</select>

you are having the problem with displaying the value from the object. retrieve the value of the object using . or you can use the []

Upvotes: 0

Related Questions