我有一个子组件,它接受 aTemplateRef
作为@Input
并通过ngTemplateOutlet
. 如何使用@ViewChild
/@ViewChildren
检索模板内的组件?
如果模板在使用它的同一组件中声明,则@ViewChild
/@ViewChildren
正在工作,但它会使组件的动态性降低。
我也尝试过使用@ContentChildren
,但没有区别。
我创建了一个 stackblitz 来重现。以下是一些代码:
child.component.html
<ng-container #fromParent [ngTemplateOutlet]="template"></ng-container>
child.component.ts
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css'],
})
export class ChildComponent implements AfterViewInit {
@Input() template: TemplateRef<unknown>;
@ViewChildren(HelloComponent) hello = new QueryList<HelloComponent>();
ngAfterViewInit() {
console.log('Has hello', this.hello.length > 0);
}
}
父组件.html
<ng-template #tmp> <hello name="{{ name }}"></hello> </ng-template>
<app-child [template]="tmp"> </app-child>
登录子组件返回false
.
这是堆栈闪电战:https ://stackblitz.com/edit/angular-eopzyw?file=src/app/app.component.ts
谢谢你。