首页 > 解决方案 > 角度,通过传递的引用访问本机元素

问题描述

我可以将 ElementRef 传递给子组件,然后在那里访问它的 nativeElement 吗?我得到了 html 元素,但我无法访问 nativeElement。我可以做些什么来访问 nativeElement 或如何直接传递它?

父模板:

<tr #refTr1>
  <app-cell [parentRef]="refTr1"></app-cell>
</tr>

子组件“appCellComponent”:

@Input parentRef: ElementRef;

ngOnInit(): void {
  console.log(this.parentRef.nativeElement.classList);
}

标签: angular

解决方案


你在 @Input 装饰器之后忘记了 ()

并且您的属性类型是 HTMLTableRowElement;

@Input() parentRef: HTMLTableRowElement;

而且你不需要在this.parentRef之后使用nativeElement


推荐阅读