如何使用Angular 2使用选择下拉列表过滤数据?

问题描述 投票:1回答:2

我想根据使用角度2的表内的下拉选择来显示JSON数据中的不同值。

<div>
    <label for="input-one">select</label>
</div>
<div>
    <select>
        <option value="">--- Select ---</option>
        <option value="ABC">ABC</option>
        <option value="def">def</option>
   </select>
</div>

例如:

如果选择ABC,则应显示与表中的JSON数据匹配的ABC值。如果选择def,它应该显示来自表中JSON数据的匹配值。

我想在Angular 2中这样做。请告诉我可能是什么解决方案。

angular angular2-forms angular2-directives
2个回答
6
投票

最简单的方法是将selectngModel绑定,并将选择值传递给与对象匹配的函数。

示例html:

<div>
    <select [(ngModel)]="selected" (ngModelChange)="onSelect(selected)">
        <option *ngFor="let option of options" 
                [value]="option"> 
          {{ option }}
        </option>
   </select>
</div>
<p></p>
<div>Selected Option</div>
<div>{{ selected }}</div>

<table>
  <th>Value</th>
  <th>id</th>
  <tr *ngFor="let x of selectedData">
    <td>{{x?.value}}</td>
    <td>{{x?.id}}</td>
  </tr>
</table>

样本组件:

someData = [{ value: "ABC",id:"123"},
          { value: "ABC",id:"12"},
          { value: "DEF",id:"23"},
          { value: "DEF",id:"1233"},
          { value: "ABC",id:"13"},
          { value: "DEF",id:"1"},
          { value: "DEF",id:"34"},
          { value: "ABC",id:"56"},
          { value: "ABC",id:"13"},
          { value: "DEF",id:"123"},
          { value: "HIJ",id:"113"}]

options =['ABC', 'DEF']

selected;
selectedData;

constructor(){
  this.selectedData = this.someData;
}

onSelect(val){
  console.log(val);
  this.selectedData = this.someData.filter(x => x.value == val)
}

demo


0
投票

真正基本的实现将在select标签和onChange函数上添加双向绑定

<div>
    <label for="input-one">select</label>
</div>
<div>
    <select [{ngModel}]="someProperty" (change)="changeTableContent()">
        <option value="">--- Select ---</option>
        <option value="ABC">ABC</option>
        <option value="def">def</option>
   </select>
</div>

您的属性将具有所选的选项值,然后您可以使用表格内容执行任何操作。表内容过滤器的实现并不那么容易,因此我建议您使用第三方工具。

在onChange函数中,你可以像这样实现一些

public changeTableContent() {
   if(this.someProperty === 'ABC') {
    //Get the json data and add it into the table.
   }
}

不要忘记将FormsModule添加到您正在实现此功能的模块,因为ngModel是FormsModule的一部分。

© www.soinside.com 2019 - 2024. All rights reserved.