html - 访问父 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>
解决方案
如果您知道,通过使用 JS/TS,您想要设置样式的元素是哪个元素,那么您可能想要使用element.closest(<selector>)
函数。它将提供对具有特定类的最近父容器的访问权限。然后你可以给它一个额外的类。
推荐阅读
- php - 如何隐藏价格高于1的产品
- laravel - Laravel 如何将值更新到另一个表中的另一列?
- xamarin - Xamarin Forms Android Iframe 导航事件未触发
- python - 如何在“if”语句中调用函数?
- python - 在 Python 中使用 yfinance 从 Yahoo Finance 下载股票价格数据时出错
- python - 使用 python gdal 从字节数据中保存图像
- python - Python - 矩阵乘法代码问题
- openssl - 从 UEFI 创建签名证书请求和验证证书的最佳方式
- xamarin - Xamarin:从 Visual Studio 将 iOS 发布到 App Store 不起作用
- ios - RealityKit 让我的 iPhone 热状态无缘无故地发疯