角度过滤列表

时间:2021-06-11 08:51:40

标签: javascript html angular typescript

在我的代码中,当从组合框中选择一个选项时,我试图过滤元素列表。我的代码如下。现在,代码没有任何错误,但我无法成功过滤列表。我该怎么办?

HTML:

<mat-form-field appearance="outline" fxFlex fxFlex.gt-sm="50" class="pr-4">
                                <mat-label>Document Type</mat-label>
                                <mat-select [(ngModel)]="sourceType" (ngModelChange)="searchTransaction()">
                                    <mat-option *ngFor="let dp of sourceTypeList" [value]="dp">
                                        {{dp.Name}}
                                    </mat-option>
                                </mat-select>
                            </mat-form-field>

TS:

     sourceTypeList: IBasicModel[];
     sourceType: IBasicModel;
    stockTransactionList: IStockTransaction[] = [];

    searchTransaction() {
            if (this.stockTransactionList && this.stockTransactionList.length > 0) {
                let stockTransactionSearchData: IStockTransaction[] = [
                    ...this.stockTransactionList,
                ];
//FILTER FOR SOURCE TYPE
                if(this.sourceType){
                    stockTransactionSearchData = stockTransactionSearchData.filter((x) => x.SourceType.Id);
                }
    
                //Default
                this.dataSourceStockTransactions.data = [...stockTransactionSearchData,];
            }
        }

2 个答案:

答案 0 :(得分:1)

我认为您没有比较已实施的过滤器中的选定类型。

我创建了一个示例,试图在 Stackblitz 上复制您的案例,您会在那里找到完整的示例。


  sourceTypeList: IBasicModel[] = [
    { id: 1, category: 'finance' },
    { id: 2, category: 'housing' }
  ];
  sourceType: IBasicModel;
  stockTransactionList: IStockTransaction[] = [
    { id: 1, info: 'tr1', sourceType: { id: 1, category: 'finance' } },
    { id: 2, info: 'tr2', sourceType: { id: 2, category: 'housing' } },
    { id: 1, info: 'tr3', sourceType: { id: 1, category: 'finance' } },
    { id: 2, info: 'tr4', sourceType: { id: 2, category: 'housing' } },
    { id: 1, info: 'tr5', sourceType: { id: 1, category: 'finance' } },
    { id: 2, info: 'tr6', sourceType: { id: 2, category: 'housing' } }
  ];

 //FILTER FOR SOURCE TYPE
      if (this.sourceType) {
        stockTransactionSearchData = stockTransactionSearchData.filter(
          x => x.sourceType.id === this.sourceType.id // the comparison 
        );
      }

这应该有效。

答案 1 :(得分:0)

我认为您可以使用 FormControl 并订阅 valueChanges。

sourceTypeControl = new FormControl('');

constructor() {
  this.sourceTypeControl.valueChanges.subscribe(value => {
    // ...
    console.log(value);
    if (value) {
      // stockTransactionSearchData = stockTransactionSearchData.filter((x) => x.SourceType.Id);
    }
  })
  }
<mat-form-field>
  <mat-label>Document Type</mat-label>
  <mat-select [formControl]="sourceTypeControl">
    <mat-option *ngFor="let dp of sourceTypeList" [value]="dp">
      {{dp.Name}}
    </mat-option>
  </mat-select>
</mat-form-field>

我创建了一个 Stackblitz,您必须根据自己的特定行为进行调整。