如何根据第一个下拉菜单的选择过滤第二个下拉菜单?-角度 [英] How to filter second dropdown based on selection of first dropdown? - Angular

查看:49
本文介绍了如何根据第一个下拉菜单的选择过滤第二个下拉菜单?-角度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个下拉菜单,如下所示:

I have a two dropdowns that looks like this:

所以我的计划是加载所有子类别,但是我只想在下拉列表中显示与所选类别(那些包含ParentId作为所选类别的ID的类别)相关的子类别.

so my plan is to load all subcategories, but I would like to display in dropdown only these which are related to selected Category ( that one which contain ParentId as Id of selected Category).

这是我的代码:

<!--Category-->

<div class="form-group">
  <label class="control-label dash-control-label col-xs-3">Category:</label>
  <div class="col-xs-9">
    <select class="form-control select2" style="width: 100%;"
            data-minimum-results-for-search="Infinity" name="articleCategory" #articleCategory="ngModel" required [(ngModel)]="article.mainCategory">
      <option disabled [ngValue]="null">-/-</option>
      <option [ngValue]="category" *ngFor="let category of mainGroups">{{category.title}}</option>
    </select>
  </div>
</div>

<!--Subcategory-->

<div class="form-group">
  <label class="control-label dash-control-label col-xs-3">Sub category:</label>
  <div class="col-xs-9">
    <select class="form-control select2" style="width: 100%;" name="subCategory" #subCategory="ngModel" required [(ngModel)]="article.subCategory">
      <option disabled [ngValue]="null">-/-</option>
      <option [ngValue]="subcategory" *ngFor="let subcategory of subCategories">{{subcategory.title}}</option>
    </select>
  </div>
</div>

如果我需要发布打字稿代码,请告诉我,但是这里我从数据库中获取了值,这对我来说只是一个问题,如何根据类别选择过滤子类别.

If I need to post typescript code please tell me, but Here I got values from database, and this is only problem for me, how to filter Subcategory based on Category selection.

谢谢大家干杯!

推荐答案

正如一些注释所指出的那样,请听您第一个select元素的更改,以便使用 filter .

As some of the comments pointed out, listen to the change of you first select element to dynamically generate the options for you second select with a filter.

类似的东西:

filterSubById(id) {
    return this.subCategories.filter(item => item.parentId === id);
}

我已经做了一个工作演示的快速演示.

I've made a quick working demo to show how.

编辑

此方法的工作方式是,将第一个选择中的选定值绑定到组件的 mainCategory 属性.因此, mainCategory 会根据用户从第一个菜单中选择的内容进行更改.第二个选择项根据用户在第一个选择项上的选择动态加载选项.这是通过 filter 函数完成的,该函数返回 subCategories 数组中其 parentId id 匹配的所有元素.在第一个菜单中选择的选项.

The way this works is that the selected value from the first select is bound to the mainCategory property of your component. Hence, mainCategory changes depending on what the user selects from the first menu. The second select dynamically loads the options depending on what the user chooses on the first one; this is accomplished with a filter function that returns all the elements in the subCategories array whose parentId matches the id of the option selected in the first menu.

这篇关于如何根据第一个下拉菜单的选择过滤第二个下拉菜单?-角度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆