如何在angular2中的不同选择框中过滤对象

时间:2017-01-03 11:03:04

标签: angular

    batchObj:any= [
              {'batch':'28','term':'Term I','section':'Section I'},
              {'batch':'28','term':'Term I','section':'Section II'},
              {'batch':'28','term':'Term I','section':'Section III'},
              {'batch':'28','term':'Term II','section':'Section I'},
              {'batch':'29','term':'Term I','section':'Section I'},
              {'batch':'29','term':'Term I','section':'Section II'},
              {'batch':'30','term':'Term I','section':'Section I'},
              {'batch':'31','term':'Term I','section':'Section I'}   
              ];

HTML

    Batch : <select  [(ngModel)]="sel_batch" > <option >Select Batch</option>
                       <option *ngFor="let item of batchObj;">{{item.batch}}</option>
                </select>
        Term : <select  [(ngModel)]="sel_term"> <option>Select Term</option>
         <option *ngFor="let item of batchObj;">{{item.term}}</option>
         </select>           
        Section : <select  [(ngModel)]="sel_section"> <option>Select Section</option> 
         <option *ngFor="let item of batchObj;">{{item.section}}</option>
        </select> 

当页面加载distinct batch存储在sel_batch select box中,然后当选择batch时,相关的term应显示在term select box section select box的同一作品中当term选择

如何在角度2中做到这一点?

1 个答案:

答案 0 :(得分:2)

您可以使用angular2管道

现在html将是

Batch : <select  [(ngModel)]="sel_batch" > <option >Select Batch</option>
                       <option *ngFor="let item of batchObj| filterPipe;">{{item.batch}}</option>
                </select>
        Term : <select  [(ngModel)]="sel_term"> <option>Select Term</option>
         <option *ngFor="let item of batchObj | filterPipe: ['batch', sel_batch, 'term'];">{{item.term}}</option>
         </select>           
        Section : <select  [(ngModel)]="sel_section"> <option>Select Section</option> 
         <option *ngFor="let item of batchObj | filterPipe: ['term', sel_term, 'section'];">{{item.section}}</option>
        </select> 

和filterPipe.ts将是

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
    name: 'filterPipe'
})

export class filterPipe implements PipeTransform {
    transform (value: Array<any>, args?: any) {
        let filterArray = [];
        let filterArray1 = [];
        if (args) {
            filterArray1 = value.filter(function(val, key) {
              if (val[args[0]] === args[1] && filterArray.indexOf(val[args[2]]) < 0) {
                filterArray.push(val[args[2]]);
                return true;
              } else {
                return false;
              }
            });
        } else {
            filterArray1 = value.filter(function(val, key) {
            if (filterArray.indexOf(val.batch) < 0) {
                filterArray.push(val.batch);
                return true;
            } else {
                return false;
            }
            });
        } 
        return filterArray1;
    }
}

在声明中包含filterPipe。试试这个