【问题标题】:Angular filtering with dropdown带有下拉菜单的角度过滤
【发布时间】:2019-03-09 18:38:28
【问题描述】:

我有以下代码:

HTML:

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

一些 Angular 服务:

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

];

还有一些过滤函数,按类型过滤数组并返回新数组。

我没有遇到按如下按钮过滤的问题:

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

但我不能使用下拉菜单。

UPD:解释不正确。 Here 现场演示。需要使用brandName在选择标签处过滤带有(更改)事件的数组

【问题讨论】:

  • 您能具体说明一下这个问题吗?

标签: javascript angular filtering


【解决方案1】:

设置ngModel 获取选定值,设置change 事件更新列表:

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

然后在值发生变化时过滤组件中的项目:

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

Demo

【讨论】:

  • 谢谢,但我需要过滤另一个数组。错误地表达了我的想法
  • 非常感谢。这比我想象的要容易。
  • @Shiv,我更新了演示的链接。它是由其他人添加的,并且是问题中演示的精确副本。我从我的答案中添加了复制的代码,它似乎有效。
【解决方案2】:

试试这个

AppComponent.ts 文件

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>

您在显示对象的值时遇到问题。使用. 检索对象的值,或者您可以使用[]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-15
    • 2023-03-24
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多