Я пытаюсь написать компонент, который может динамически содержать разные компоненты. Моя цель - написать статью, в которой я мог бы написать абзац или добавить твит.
Это код для DynamicArticleComponent
:
@Directive({
selector: '[dynamic-query]'
})
export class QueryDirective {
constructor(public viewContainerRef: ViewContainerRef) {}
}
@Component({
selector: 'app-dynamic-article',
template:
`<ng-container *ngFor="let element of elements">
<ng-template dynamic-query></ng-template>
</ng-container>`,
styleUrls: ['dynamic-article.component.css']
})
export class DynamicArticleComponent implements AfterViewInit {
@Input() elements: Element[];
@ViewChildren(QueryDirective) queryDirectives;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
ngAfterViewInit() {
this.queryDirectives.forEach((queryDirective: QueryDirective, index) => {
const element = this.elements[index];
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(element.component);
const containerRef = queryDirective.viewContainerRef;
containerRef.clear();
const newComponent = containerRef.createComponent(componentFactory);
(<DynamicComponent>newComponent.instance).data = element.data;
});
}
}
Это другие классы, используемые в коде выше:
export class Element {
constructor(public component: Type<any>, public data) {}
}
export interface DynamicComponent {
data: any;
}
У меня проблемы с рендерингом <ng-templates>
. Он просто отображает комментарии и не изменяется после загрузки представления. Вот что отображается: 
Элементы правильно попадают в компонент. Моя идея состоит в том, чтобы визуализировать все шаблоны, затем получить их с помощью декоратора ViewChildren и отобразить элементы там, где они должны быть. Есть ли другое решение этой проблемы?
Кроме того, вот как элементы достигают DynamicArticleComponent
:

Заранее спасибо.