在Angular 9中,如果你想在使用ng-container和ngIf添加元素后获取父节点,你可以使用ViewChild装饰器来获取父节点的引用。以下是一个解决方法的代码示例:
在父组件的HTML模板中,使用ng-container和ngIf来添加元素:
Child Element
在父组件的 TypeScript 文件中,使用ViewChild装饰器来获取父节点的引用:
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements AfterViewInit {
@ViewChild('parentContainer', {static: false}) parentContainer: ElementRef;
showChildElement = true;
ngAfterViewInit() {
console.log(this.parentContainer.nativeElement); // 输出父节点的引用
}
}
在上述代码中,我们使用ViewChild装饰器获取了父节点的引用,并在ngAfterViewInit生命周期钩子中打印了父节点的引用。请确保将ViewChild装饰器应用在父组件的类成员变量上,并使用{static: false}
选项来指定在视图初始化后获取父节点的引用。
当showChildElement为true时,ng-container中的子元素会被添加到父节点中。在ngAfterViewInit中,你可以通过this.parentContainer.nativeElement来访问父节点的引用,并进行进一步的操作。
希望这个解决方法对你有所帮助!