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

How to filter data with select dropdown using Angular 2?

我想显示来自 JSON 数据的不同值,具体取决于使用 angular 2.

table 内的下拉 selection
<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>

例如:

如果您 select ABC,它应该显示与 table 中 JSON 数据中的 ABC 相匹配的值。如果您 select def,它应该显示 table.

中 JSON 数据的匹配值

我想在 Angular 2 中执行此操作。请告诉我可能的解决方案。

真正的基本实现是在 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>

您的 属性 将具有 selected 选项值,您可以随心所欲地使用 table 内容。 table内容过滤器的实现不是那么容易,所以我最好建议你使用第三方工具。

onChange函数中,你可以这样实现

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

不要忘记将 FormsModule 添加到您正在实现此功能的模块中,因为 ngModelFormsModule.

的一部分

最简单的方法是将 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>

样本component.ts:

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