Reputation: 390
In my code, I'M trying to filter a list of elements when an option is selected from a combobox. My code is below. Right now, the code doesn't have any errors, but I couldn't succeed on filtering the list. What should I do?
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,];
}
}
Upvotes: 0
Views: 931
Reputation: 616
I think you are not comparing the selected type in the filter that you have implemented.
I created an example trying to replicate your case on Stackblitz, you'll find the complete example there.
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
);
}
This should work.
Upvotes: 1
Reputation: 2761
I think you can use FormControl
and subscribe to 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>
I've created a Stackblitz which you'll have to adapt for your specific behavior.
Upvotes: 0