在Angular中,ElementRef只能访问组件的本地DOM元素。如果你想要访问父组件的DOM元素,你可以使用ViewContainerRef。
这是一个例子:
import { Component, ViewContainerRef } from ‘@angular/core’;
@Component({
selector: ‘app-child’,
template: <div #childDiv>Child</div>
})
export class ChildComponent {
constructor(private viewContainerRef: ViewContainerRef) {}
ngAfterViewInit() {
const parentElement = this.viewContainerRef.element.nativeElement.parentNode;
console.log(parentElement); // This will log the parent element of the component in the DOM
}
}
在这个例子中,我们注入了ViewContainerRef,然后在ngAfterViewInit生命周期钩子中使用它来获取父元素。