Issue
I'm using Angular material's AutoComplete as follows
<form class="form">
<mat-form-field class="search-user">
<mat-label>User</mat-label>
<input type="text" matInput [formControl]="userCtrl" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
@if(userCtrl.value?.length < 3) {
<div class>Type 3 or more characters</div>
} @else if(isLoading) {
<div>loading...</div>
} @else if (!(filteredOptions | async)?.length) {
<div class>No match found</div>
}
@for (option of filteredOptions | async; track option) {
<mat-option [value]="option">{{option}}</mat-option>
}
</mat-autocomplete>
</mat-form-field>
</form>
This is more or less a copy-past from one of their examples.
But what I would like to add is text above the options (inside the overlay) if there are no options (yet)
@if(userCtrl.value?.length < 3) {
<div class>Type 3 or more characters</div>
} @else if(isLoading) {
<div>loading...</div>
} @else if (!(filteredOptions | async)?.length) {
<div class>No match found</div>
}
However, the overlay is closed when there are 0 options. Is there a way, such that I can show/activate the overlay when the input has focus and 0 options (empty array)? But when the user select an options, the focus is lost and the overlay closes
Solution
You can use disabled <mat-option>
elements (might need to play around with the *ngIf
conditions to get exactly the right behavior):
<form class="form">
<mat-form-field class="search-user">
<mat-label>User</mat-label>
<input type="text" matInput [formControl]="userCtrl" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
<mat-option disabled *ngIf="userCtrl.value?.length < 3">Type 3 or more characters</mat-option>
<mat-option disabled *ngIf="isLoading">Loading...</mat-option>
<mat-option disabled *ngIf="(filteredOptions | async)?.length === 0">No match found</mat-option>
<ng-container *ngIf="userCtrl.value?.length >= 3">
<mat-option *ngFor="option of filteredOptions | async; track option" [value]="option">{{option}}</mat-option>
</ng-container>
</mat-autocomplete>
</mat-form-field>
</form>
Answered By - codequiet
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.