bigb055
bigb055

Reputation: 308

mat-select panelOpen always false

I have following template:

  <mat-select #select>
      <mat-option *ngFor="let option of optionsData">
        {{ select.panelOpen ? option.viewValue : option.value }}
      </mat-option>
  </mat-select>

And following test which fails:

it('should populate options list with view values', async () => {
    const expected = optionsData.map(o => o.viewValue);
    const select = de.query(By.css('.mat-select')).nativeElement;

    select.click();
    fixture.detectChanges();

    await fixture.whenStable().then(() => {
      for (const option of select.children) {
        expect(expected.findIndex(e => e === option.textContent)).toBeGreaterThan(-1);
      }
    });
  });

But if I change first line in the test to:

const expected = optionsData.map(o => o.value)

Then the test would pass. That means panelOpen is always false and is only getting the value instead of the viewValue, even though I clicked on the 'select' element.

Why does click() not change panelOpen from false to true?

Upvotes: 0

Views: 1108

Answers (1)

roniccolo
roniccolo

Reputation: 158

I fixed this issue with a directive

import { OnInit, Directive, EventEmitter, Output } from '@angular/core';
import { MatSelect } from '@angular/material/select';

@Directive({
  selector: '[athMatOptionDirective]'
})
export class MatOptionDirective implements OnInit {
  @Output() matOptionState: EventEmitter<any> = new EventEmitter();
  constructor(private matSelect: MatSelect) { }
  ngOnInit() {
    this.matSelect.openedChange.subscribe(isOpen => {
      if(isOpen) return this.matOptionState.emit(true)
      return this.matOptionState.emit(false)
    })
  }
}

in your html component:

<mat-form-field>
  <mat-select athMatOptionDirective (matOptionState)="getMatOptionState(event)">
  </mat-select>
</mat-form-field

typescript component:

getMatOptionState(event) {
   console.log('is mat-option open?', event)
}

Many thanks to Juri Strumpflohner (https://juristr.com/blog/2020/06/access-material-select-options) example here: stackblitz

Upvotes: 1

Related Questions