4
votes

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:

But I get:

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

This is how I want it to work:

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

2

2 Answers

9
votes

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.

0
votes

With a little hack you could simply replace the suggestions by an empty array when the slide is checked :

<mat-autocomplete  #auto="matAutocomplete">
      <mat-option *ngFor="let state of (slide.checked ? [] : (filteredStates| async)) " 
[value]="state.name">
...

Here is an edit of your stackblitz.