So I have an Angular 5 Material Data Table with on it 2 filter options, one via text input and one via dropdown to filter on a particular field value. For the dropdown I use a "mat-select" Angular Material item with in it 2 mat-options, one empty and one based on an array I have, like so:
<div class="filterContainer" *ngIf="showDataForm">
<mat-form-field>
<input #matInputSearch matInput (keyup)="applyFilter($event.target.value)" placeholder="Search">
</mat-form-field>
</div>
<div class="filterSelectContainer" *ngIf="showDataForm">
<mat-select placeholder="Search EADDPStage" (selectionChange)="applySelectFilter($event)">
<mat-option></mat-option>
<mat-option *ngFor="let stage of EADDPStages[0]" [value]="stage">
{{stage}}
</mat-option>
</mat-select>
</div>
Here you can see my .ts code file for these:
@ViewChild(MatSelect) set contentSelect(contentSelect: ElementRef) {
this.select = contentSelect;
}
@ViewChild('matInputSearch') set matInputSearch(matInputSearch: ElementRef) {
this.matInputSearchField = matInputSearch;
}
public applyFilter(filterValue: string) {
filterValue = filterValue.trim();
filterValue = filterValue.toLowerCase();
this.dataSource.filter = filterValue;
}
public applySelectFilter(event) {
// This is to reset dropdown filter to empty/no filter
if (event.value == null) {
event.value = '';
}
this.applyFilter(event.value);
// set the "Search" field filter to empty string
this.matInputSearchField.nativeElement.value = '';
}
What happens now in my UI is that both filters work correctly, but I want to "reset" (visually) the filters as well. Now when I type in something in my text-box filter and then select something from my dropdownlist, the text box filter's value will be set to empty as to indicate you're now filtering on the dropdown and no longer on the text input filter field, the following line does this:
this.matInputSearchField.nativeElement.value = '';
But now I want the other way to work as well. If I select a dropdown filter, it filters, but then when I want to type something in my text input filter field, the filter also works correctly but the dropdown selected option will still be the previously selected value (even though it's filter no longer applies). What I want is that in this scenario, when I type something in the text input filter field, that my select dropdown will go back to the empty option I've added in my HTML as to indicate you're no longer filtering on the dropdown selection but on what the user typed in in the input filter field.
What I basically need is a way to do something like this (this is wrong code btw but just an indication):
this.select.selectedOption('mat-option-0');
Where I select my "mat-select" item on my HTML and give it a selected option or default option of the one I want, in this case my 'mat-option-0' is the ID if the empty you see in my HTML.
Is there a easy way of doing this?
mat-select
using component.ts code? – User3250