【问题标题】:Angular 2 Get mat-dialog-container nativeelementAngular 2 获取 mat-dialog-container nativeelement
【发布时间】:2018-06-21 09:13:03
【问题描述】:

我正在使用 angular 2 material mat-dialogs。现在我想访问 mat-dialog-container 本机元素。

let nElem = this.dialogRef._containerInstance._elementRef.nativeElement;

当我尝试访问上面的本机元素时,我收到错误“Property _elementRef”是私有的,只能在类“MatDialogContainer”中访问

示例:-https://stackblitz.com/edit/angular-z5mgjl

【问题讨论】:

    标签: angular


    【解决方案1】:

    获取 Mat Dialog 的本机元素的一种简单方法是使用 ViewContainerRef。据我了解,在构造函数中使用 ViewContainerRef 将获得该组件容器的引用。在您的情况下,它将是 Mat Dialog Container。

    以下作品:

    import { ViewContainerRef } from '@angular/core';
    
    
    constructor(private _ViewContainerRef: ViewContainerRef) { 
    
    }
    
    ngOnInit() {
      let matDialogContainerRef = this._ViewContainerRef.element.nativeElement;
    }
    

    在另一个有趣的注释中,这可用于轻松识别点击是发生在对话框内部还是外部。

    @HostListener('document:click', ['$event'])
    clickout(event) {
      if(this.vcRef.element.nativeElement.contains(event.target)) {
        alert('Clicked inside');
      } else {
        alert('Clicked outside');
      }
    }
    

    【讨论】:

      【解决方案2】:

      以下在 Angular 5 项目中对我有用

       let nElem = dialogRef['_containerInstance']['_elementRef'].nativeElement;
      

      希望它有效。

      【讨论】:

      • 您好 Dimitri,您的回答确实有效,但是这样进入私有变量并不好。
      • 这可以在--prod 构建中工作吗?我猜不是,当然在当前的 Angular 中
      猜你喜欢
      • 1970-01-01
      • 2018-10-28
      • 2018-12-20
      • 2020-06-25
      • 1970-01-01
      • 2020-07-02
      • 2021-04-22
      • 2021-11-17
      • 1970-01-01
      相关资源
      最近更新 更多