Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to optionally add material autocomplete in Angular

I want to be able to optionally add autocomplete to an input.

Currently I have tried adding an *ngIf to the mat autocomplete tag but it raises errors because the input has the matAutocomplete property and is looking for the autocomplete component. I have also tried setting matAutocomplete to null when I want autocomplete off but this did not work.

Here is what I tired:

  • https://stackblitz.com/edit/angular-3ebz9m-bw56h9?file=app/autocomplete-overview-example.html

But I get:

Error: Attempting to open an undefined instance of `mat-autocomplete`.

This is how I want it to work:

  • https://stackblitz.com/edit/angular-3ebz9m-umwj6h?file=app%2Fautocomplete-overview-example.html

But without having to duplicate the input and form field tags.

like image 928
Curtis Avatar asked Jan 03 '23 09:01

Curtis


1 Answers

The suggested "hack" works great if you always have the autocomplete component but sometimes don't have items for it. But it sounds like you want to create a custom component based on MatFormField and MatInput that can optionally use a MatAutocomplete. I've done this and there is no way around ngIf on the form field unless you use a future version of Angular Material v6. See https://github.com/angular/material2/issues/11096 (my issue). They will be fixing this in Angular Material v6 via a new directive option to disable the autocomplete - matAutocompleteDisabled. When released, you can do this:

<input matInput [matAutocomplete]="auto" [matAutocompletDisabled]="slide.checked">

So if auto is null, you won't get any errors.

like image 193
G. Tranter Avatar answered Jan 13 '23 14:01

G. Tranter