你不能像那样插入组件并访问视图(在你的代码中,模板组件是空的),你需要将它放在组件的html中,并使用视图子级进行访问,请在下面找到一个工作示例,我也更改为
ngAfterViewInit
由于模板将始终存在,如果您在
ngOnInit
该视图将被取消初始化,并将为null。
html
<p>{{ item.id }} - {{ item.name }} - {{ item.email }}</p>
<app-header [headerTemplate]="selectedTemplate" [item]="item" />
<app-templates #templates></app-templates>
ts
import { CommonModule } from '@angular/common';
import {
Component,
Input,
TemplateRef,
inject,
ViewChild,
} from '@angular/core';
import { Item } from '../services/data.service';
import { HeaderComponent } from '../header/header.component';
import { TemplatesComponent } from '../templates/templates.component';
@Component({
selector: 'app-item',
templateUrl: './item.component.html',
standalone: true,
imports: [CommonModule, HeaderComponent, TemplatesComponent],
providers: [TemplatesComponent],
})
export class ItemComponent {
@ViewChild(TemplatesComponent) templatesComponent: TemplatesComponent;
@Input() item!: Item;
selectedTemplate: TemplateRef<any> | null = null;
ngAfterViewInit() {
if (this.item.type) {
this.selectTemplate();
}
}
selectTemplate(): void {
console.log(this.templatesComponent);
if (this.item.type === 'type-a') {
this.selectedTemplate = this.templatesComponent.templateA;
} else if (this.item.type === 'type-b') {
this.selectedTemplate = this.templatesComponent.templateB;
} else if (this.item.type === 'type-c') {
this.selectedTemplate = this.templatesComponent.templateC;
}
}
}
stackblitz