I have a pretty basic autocomplete set up with Angular Material (6). Here is the basic implementation:
<mat-form-field>
<input type="text" matInput placeholder="Company" formControlName="company" [matAutocomplete]="autoCo"/>
<mat-autocomplete #autoCo="matAutocomplete" [displayWith]="displayCo">
<mat-option *ngFor="let company of filteredCompanies | async" [value]="company">
</mat-option>
</mat-autocomplete>
</mat-form-field>
That works without a problem. However, I want to have something happen when a selection is made. To do this, I added (optionSelected)="onSelectionChanged($event)" to the mat-autocomplete element. Initially, everything works as expected (filtering the options works). When a selection has been made, the onSelectionChanged function also fires as expected.
However, after a selection has been made, the selected item is the only item available in the autocomplete drop-down no matter what changes I make. So even if I delete all the text in the input, I still only see the previously selected option. I would expect to see the complete list instead.
In ngOnInit, I have:
this.filteredCompanies = this.companyForm.get("company").valueChanges.pipe(
debounceTime(200))
.pipe(mergeMap(val => this.filter(val)));
It appears that the valueChanges subscription ends if I bind to optionSelected. If I don't bind to optionSelected, the list of options updates as expected.
Am I incorrectly binding to the optionSelected event? Do I have to re-subscribe to the form valueChanges from within onSelectionChanged()?? If so, why?
For what it is worth, here is some other relevant code:
@Output()
optionSelected = new EventEmitter();
onSelectionChanged(event: any) {
console.log(event);
this.optionSelected.emit(event);
}
from Angular Material binding to event cancels valueChanges subscription
No comments:
Post a Comment