获取angular2组件的父DOM元素引用可以通过以下步骤实现:
import { Component, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'app-child-component',
template: '<div #parentElementRef></div>',
})
export class ChildComponent {
@ViewChild('parentElementRef', { read: ElementRef }) parentElementRef: ElementRef;
}
<div>
<app-child-component></app-child-component>
<div #parentElementRef></div>
</div>
import { Component, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'app-parent-component',
template: '<app-child-component></app-child-component>',
})
export class ParentComponent {
@ViewChild('parentElementRef', { read: ElementRef }) parentElementRef: ElementRef;
ngAfterViewInit() {
console.log(this.parentElementRef.nativeElement);
}
}
以上代码中,ParentComponent通过ViewChild装饰器获取了ChildComponent中标记为parentElementRef的父DOM元素的引用,并在ngAfterViewInit钩子函数中打印出了该引用。
应用场景:
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云