【问题标题】:mat-select panelOpen always false垫选择面板打开总是假
【发布时间】:2021-11-16 17:55:45
【问题描述】:

我有以下模板:

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

以下测试失败:

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);
      }
    });
  });

但如果我将测试中的第一行更改为:

const expected = optionsData.map(o =&gt; o.value)

那么测试就会通过。这意味着 panelOpen 始终为 false,并且仅获取 value 而不是 viewValue,即使我单击了“选择”元素。

为什么 click() 不会将 panelOpen 从 false 更改为 true?

【问题讨论】:

    标签: angular unit-testing angular-material jasmine mat-select


    【解决方案1】:

    我用指令解决了这个问题

    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)
        })
      }
    }
    

    在您的 html 组件中:

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

    打字稿组件:

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

    非常感谢 Juri Strumpflohner (https://juristr.com/blog/2020/06/access-material-select-options) 此处示例:stackblitz

    【讨论】:

      猜你喜欢
      • 2019-04-05
      • 1970-01-01
      • 2020-04-30
      • 2016-08-15
      • 2021-03-20
      • 2018-10-10
      • 1970-01-01
      • 2021-04-11
      • 1970-01-01
      相关资源
      最近更新 更多