3
votes

I have an input instructorControl = new FormControl(); with an autocomplete. The autocompelte subscribes to this.instructorControl.valueChanges. When a suggestion from the autocomplete is selected or the add button is clicked, the current input value is pushed to an array and the input cleared with this.instructorControl.patchValue('');.

When an autocomplete option is selected, the autocomplete options menu is not opened again. For that, you either have to type something in or refocus the input.

How can I make the autocomplete reopen, when a suggestion is selected?

See this stackblitz. (Updated Sep 18)

app.component.html

  <button md-button (click)="addInstructor()">add</button>
  <md-input-container fxFlex>
    <input mdInput name="instructor" placeholder="instructor" (keydown.enter)="addInstructor()" [mdAutocomplete]="instructorsAuto" [formControl]="instructorControl">
  </md-input-container>


  <md-autocomplete #instructorsAuto="mdAutocomplete">
    <md-option *ngFor="let instructor of filteredInstructors | async" [value]="instructor" (click)="addInstructor()">
      {{ instructor }}
    </md-option>
  </md-autocomplete>

  {{instructors | json}}

app.component.ts

  instructors: string[] = [];
  instructorControl = new FormControl();
  filteredInstructors: Observable<string[]>;
  allInstructors = ['Max', 'Tirrell'];;
  instructorsAuto;

  ngOnInit() {
    this.filteredInstructors = this.instructorControl.valueChanges
      .startWith('')
      .map(value => this.filterInstructors(value));
  }

  addInstructor() {
    const instructor: string = this.instructorControl.value;
    if (instructor) {
      this.instructors.push(instructor);
      this.instructorControl.patchValue('');
    }
  }

  private filterInstructors(value: string = ''): string[] {
    return this.allInstructors.filter(instructor => new RegExp(`${value}`, 'gi').test(instructor));
1
I updated the plunker from yurzui's answer in this stackblitz: stackblitz.com/edit/angular-x6hftl-fuxf8s?file=app/…Kim Kern

1 Answers

8
votes

My suggestion is using @ViewChild decorator to get hold of MdAutocompleteTrigger instance and then fire openPanel() method on it.

In order to do this:

1) Add template reference variable to input[autocomplete] element:

<input #trigger ...
       [mdAutocomplete]="instructorsAuto"
       [formControl]="instructorControl">

2) Declare decorated by @ViewChild property.

import { MdAutocompleteTrigger } from '@angular/material'
...
@ViewChild('trigger', { read: MdAutocompleteTrigger }) trigger: MdAutocompleteTrigger;
                        ^^^^^^^^^^^^^^^^^^^^^^^^^
         make sure you're getting the right instance from template reference

3) Use it in your addInstructor method:

this.trigger.openPanel();

Stackblitz Example (Updated Sep 2018)