在Angular 6中,ng-template是一个用于渲染内容的容器,它不会在DOM中创建任何元素。因此,如果你在ng-template内使用ViewChild,它将返回null。这是因为ViewChild是通过查询DOM元素来获取引用,而ng-template不会创建DOM元素。
要解决这个问题,你可以使用ng-content来替代ng-template。ng-content允许你在组件模板中插入内容,并且它会在DOM中创建相应的元素。
下面是一个示例代码,演示了如何使用ng-content来解决ViewChild为null的问题:
在父组件的模板中,使用ng-content来插入子组件的内容:
在子组件中,使用@ContentChild来获取插入的内容:
import { Component, ContentChild, AfterContentInit } from '@angular/core';
@Component({
selector: 'child-component',
template: ' '
})
export class ChildComponent implements AfterContentInit {
@ContentChild('contentRef') contentRef: ElementRef;
ngAfterContentInit() {
console.log(this.contentRef);
}
}
在父组件中,使用子组件,并在ng-content上添加一个模板引用变量:
Content
现在,当子组件初始化后,contentRef将不再为null,而是会正确地引用插入的内容。
希望这可以帮助你解决问题!