单击按钮时使用自定义管道的角度过滤器表

Dre*_*w13 2 html typescript angular2-pipe angular

我有一个表格,我使用自定义管道成功过滤了它。过滤器基于两个输入,它们共同构成一个表单。我要添加的功能是在单击提交按钮之前不会进行过滤。所以它更像是一个搜索按钮。我发现了大量有关管道的信息,但没有关于在单击按钮时激活它们的信息。

主页.component.html:

<div>
  <label>Start Date:</label>
  <input type="text" [(ngModel)]="startDateValue">
</div>
  <label>End Date:</label>
  <input type="text" [(ngModel)]="endDateValue">
</div>
//'let idx=index' and 'let even=even' are used to change color of the rows but I took out that code. The 'onClick' function just takes the row and uses an EventEmitter to output it.
<tr *ngFor="let dPoint of theData | searchDates:startDateValue:endDateValue; let idx=index; let even=even;" (click)="onClick(dPoint, idx)">
  <td>{{dPoint.tDataPoint}}</td>
  <td>{{dPoint.tICCP}}</td>
  <td>{{dPoint.tStartDate}}</td>
  <td>{{dPoint.tEndDate}}</td>
</tr>
//the button that will execute the filtering
<button type="submit" class="btn icon-search" [disabled]="!secondForm.valid" (click)="submit(secondForm.value)"></button>
Run Code Online (Sandbox Code Playgroud)

mainpage.component.ts:

@Component({
  selector: 'main-page',
  styleUrls: ['../app.component.css'],
  templateUrl: 'mainpage.component.html',
  providers: [DataTableService, DatePipe]
})

export class MainPageComponent implements OnInit {
  secondForm : FormGroup;
  theData:DataTable[] = [];

  constructor(fb: FormBuilder, private datePipe: DatePipe, private dataService: DataTableService, private cdRef:ChangeDetectorRef){
    this.secondForm = fb.group({
      'startDate' : [null, Validators.required],
      'endDate' : [null, Validators.required]
    }, {validator: this.endDateAfterOrEqualValidator})
  }

  getTable(): void {
    this.dataService.getTable().then(theData => this.theData = theData);
    this.cdRef.detectChanges();
  }

  submit(value: any){
      //where I'd want to trigger the filtering/pipe
  }
}
Run Code Online (Sandbox Code Playgroud)

搜索pipe.ts:

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

@Pipe({
  name: "searchDates"
})

export class SearchPipe implements PipeTransform {
  transform(value, minDate , maxDate){
    return value.filter(row => {
      return row.tStartDate >= minDate && row.tEndDate <= maxDate;
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

Deb*_*ahK 5

您可以考虑删除管道,而是在用户单击按钮时自己过滤数据。

首先,定义表示过滤结果的第二个属性

let theFilteredData: DataTable[]
Run Code Online (Sandbox Code Playgroud)

更改您的绑定以绑定到过滤数据:

*ngFor="let dPoint of theFilteredData;" //rest of *ngFor not included
Run Code Online (Sandbox Code Playgroud)

在提交函数中:

this.theFilteredData = this.theData.filter(row => 
      return row.tStartDate >= minDate && row.tEndDate <= maxDate);
Run Code Online (Sandbox Code Playgroud)