【问题标题】:Mat select click outside not working, when drop down close当下拉关闭时,垫选择点击外部不起作用
【发布时间】:2018-11-14 20:32:44
【问题描述】:

我使用 Mat select angular 组件制作了下拉菜单,当我在下拉菜单(页面主体)之外单击时需要触发一个事件。

<mat-select #select multiple (change)="onSubmit($event)" [(ngModel)]="emp">
    <mat-option *ngFor="let value of filter.default" [value]="value">
        {{value}}
    </mat-option>
</mat-select>

这是我的 ts 文件

export class AnotherComponent {
  public text: String;

  @HostListener('document:click', ['$event'])
  clickout(event) {
    if(this.eRef.nativeElement.contains(event.target)) {
      console.log("clicked inside");
    } else {
      console.log("clicked outside");
    }
  }

  constructor(private eRef: ElementRef) {

  }
}

它不能正常工作,请帮助

【问题讨论】:

  • 你的意思是不能正常工作?
  • 如果我点击打开下拉选项,在控制台也显示“点击外部”,只有在下拉关闭时才会显示,请告知
  • 使用 if(!this.eRef.nativeElement.contains(event.target))
  • 如果我点击打开下拉菜单,它还会在控制台中显示“点击外部”。
  • 排除特定元素的任何方式

标签: javascript angular angular5 angular-material-5


【解决方案1】:

如果您想知道选择面板何时关闭,请使用openedChange 事件:

<mat-select #select multiple (change)="onSubmit($event)" [(ngModel)]="emp"
    (openedChange)="openedChange($event)">
    <mat-option *ngFor="let value of filter.default" [value]="value">
        {{value}}
    </mat-option>
</mat-select>


openedChange(opened: boolean) {
    console.log(opened ? 'opened' : 'closed');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-02
    • 2016-06-13
    • 2017-02-12
    • 2017-03-23
    • 2012-07-03
    • 1970-01-01
    相关资源
    最近更新 更多