单击叠加层时关闭弹出窗口-错误TypeError:无法读取未定义的属性'nativeElement'

时间:2019-02-21 12:39:16

标签: angular typescript

我有一个模式弹出窗口。如何通过正确单击叠加来关闭弹出窗口?错误TypeError:无法读取未定义的属性'nativeElement'

export class PopupComponent {
      @ViewChild('window') popup: ElementRef;
      visible = false;
      openPopup: boolean;
      constructor() { }

      ngOnInit() {
      }

      overlayClicked(event) {
        if(event.path.indexOf(this.popup.nativeElement) === -1){
          this.visible = false;
        }
}
.window__container {
        display: block;
        position: absolute;
        min-width: 360px;
        z-index: 10000;
}
.overlay {
        position: fixed;
        display: none;
        width: 100%;
        height: 100%;
        z-index: 2;
        cursor: pointer;
  }
<button md-icon-button (click)="openPopup()">Open</button>

<div class="overlay" (click)="overlayClicked($event)">
  <div *ngIf="openPopup" class=window>
    <h1>Hello</h1>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

尝试在html元素中添加像“ #window”这样的ID,而不仅仅是设置类。

<div class="overlay" (click)="overlayClicked($event)">
  <div *ngIf="openPopup" #window class=window>
    <h1>Hello</h1>
  </div>
</div>