我正在根据它的类型创建动态组件。
使用上面的结构,我创建了父组件,ParagraphComponent
如果你注意到ranges
有一个type
,所以我想创建一个LinkComponent
.
有什么问题 ?
LinkComponent
被创建但不在它的父组件内,它是在ParagraphComponent
.
<rc-paragraph><p>This is paragraph</p></rc-paragraph>`
<app-link>/index.htm</app-link>
但实际上应该是这样的,
<rc-paragraph>
<p>This is paragraph <app-link>/index.htm</app-link></p>
</rc-paragraph>
下面是渲染组件的代码,
private renderReactiveContent(content, container: ViewContainerRef) {
// resolve content['_type'] to factory
var type: Type<any>;
if (content instanceof Array) {
type = this.contentMappings[content[0].type];
} else {
type = this.contentMappings[content.type];
}
if (!type) {
return;
// throw new ReferenceError(`No content mapping for type=${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 = asContentCreate(component);
cmpCreate.contentOnCreate(content);
// render embedded content
if (content && Object.keys(content).length > 0) {
const cmpEmbeddable = 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) => {
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();
}
我在这里做错了什么,请帮忙。