可以使用@ViewChild指令来访问子元素。首先,需要在父组件的HTML模板中将子组件标识为模板引用变量,如下所示:
然后,可以在父组件的类型Script文件中使用ViewChild来获取该子元素的引用并检查它是否应用了某些类:
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'parent-component',
template: ' Parent'
})
export class ParentComponent {
@ViewChild('child') child: ElementRef;
ngAfterViewInit() {
if (this.child.nativeElement.classList.contains('myClass')) {
this.child.nativeElement.parentNode.removeChild(this.child.nativeElement);
}
}
}
在上面的代码中,ngAfterViewInit函数在父组件的视图和子组件的视图都已初始化后加载。在此函数中,可以通过child.nativeElement获取子元素的引用并使用parentNode.removeChild函数删除其父级div。如果子元素包含myClass类,就会发生这种情况。
相关内容