首页 > 解决方案 > 访问父 DOM 元素

问题描述

我的项目中有多个Mat 对话框组件,我只想为其中一个添加样式。我认为根据child修改parent的唯一方法是使用 class向DOM元素添加样式。但是当我尝试通过类访问父元素时,我无法访问它。<mat-dialog-container>.mat-dialog-container.mat-dialog-container

根据这些例子,这应该有效吗?

如何通过在角度中选择使用类名来将样式应用于元素?

如何在组件模板中选择元素?

垫对话框容器

TS:

    export class UpUppdragsloggDialogComponent implements AfterViewInit {
        constructor(public dialogRef: MatDialogRef<UpUppdragsloggDialogComponent>,
            @Inject(MAT_DIALOG_DATA) public data: UppdragsloggDialogData,
            private elementRef: ElementRef) {
          }
          ngAfterViewInit(): void {
            const dom: HTMLElement = this.elementRef.nativeElement;
// I have also tried to access it with  dom.querySelector('mat-dialog-container'); instead 
            const elements = dom.querySelectorAll('.mat-dialog-container');
            console.log(elements);
            elements.forEach((domElement) => {
              domElement.classList.add('resize-container');
            });
          }

    /** 
    Other not relevant stuff in the component
    */
    }

CSS:

   /* Make dialog components resizeable  */
    .resize-container {
      resize: both; 
      overflow: auto;
      z-index: 5;
    }

如何在Angular中访问DOM 元素?(如果有什么不同,我正在使用Angular 10。 )<mat-dialog-component>

标签: htmlcssangulartypescriptdom

解决方案


如果您知道,通过使用 JS/TS,您想要设置样式的元素是哪个元素,那么您可能想要使用element.closest(<selector>)函数。它将提供对具有特定类的最近父容器的访问权限。然后你可以给它一个额外的类。


推荐阅读