【发布时间】:2019-07-15 05:58:15
【问题描述】:
根据类型,我想以角度渲染组件。
例如,使用下面的代码,我想动态呈现标题组件。
{
"type": "heading-1",
"text": "Sample Text"
}
下面是渲染动态组件的逻辑
private renderReactiveContent(content: ContentDocument, container: ViewContainerRef) {
// resolve content['_type'] to factory
const type: Type<any> = this.contentMappings[content[0].type];
if (!type) {
throw new ReferenceError(`No content mapping for type=${content[0].type}`);
}
const componentFactory: ComponentFactory<any> = this.componentFactoryResolver.resolveComponentFactory(type);
const component = container.createComponent(componentFactory, container.length, this.injector);
console.info('Component dynamically created ', component);
// content lifecycle hook: notify of new values
const cmpCreate: ContentOnCreate = asContentCreate(component);
cmpCreate.contentOnCreate(content);
// render embedded content
if (content && Object.keys(content).length > 0) {
const cmpEmbeddable: ContentEmbeddable = asContentEmbeddable(component);
if (cmpEmbeddable) {
// render in the target element of ContentEmbeddable
const childContainer = cmpEmbeddable.contentEmbeddable();
Object.keys(content).forEach((key: string) => {
const value = content[key];
// XX: recursive rendering
if (value instanceof Array) {
value.forEach((v: ContentDocument) => {
this.renderReactiveContent(v, childContainer);
});
} else {
this.renderReactiveContent(value, childContainer);
}
});
} else {
// fatal: embedded content must be hosted by ContentEmbeddable
const cmpName = component.instance['constructor'].name;
throw new TypeError([`Trying to render embedded content.`,
`${cmpName} must implement interface ContentEmbeddable`].join(' '));
}
}
component.hostView.detectChanges();
}
我不确定我在这里做错了什么,它会引发错误
ERROR TypeError: Trying to render embedded content. HeadlineComponent must implement interface ContentEmbeddable
我已经创建了 stackblitz,供参考的项目请帮助。
【问题讨论】:
标签: angular angular-components