【发布时间】:2017-09-11 04:05:31
【问题描述】:
我正在尝试在运行时动态加载模板、渲染它并从模板内绑定到动态数据。
按照 stackoverflow 问题 How to render a dynamic template with components in Angular2 和 @Linksonder 的回答,我已经启动并运行了加载和渲染部分。
现在我被困在向动态组件添加 @Input 数据并提供数据以便我可以从模板绑定到它,例如 {{ data }}。
我以这种方式扩展了ngOnChanges(),以便它添加一个带有测试inputProvider的注入器:
createComponentFactory(this.compiler, compMetadata)
.then(factory => {
let inputProviders = [{provide: 'data', useValue: '1234'}];
let resolvedInputs = ReflectiveInjector.resolve(inputProviders);
const injector = ReflectiveInjector.fromResolvedProviders(resolvedInputs, this.vcRef.parentInjector);
this.cmpRef = this.vcRef.createComponent(factory, 0, injector, []);
});
但是,尝试以这种方式访问 DynamicComponent 中的注入器会引发错误(我假设注入器无法解析):
...
import { Injector} from '@angular/core';
export function createComponentFactory(compiler: Compiler, metadata: Component): Promise<ComponentFactory<any>> {
const cmpClass = class DynamicComponent {
data: any;
constructor(private injector: Injector) {
this.data = this.injector.get('data');
}
};
const decoratedCmp = Component(metadata)(cmpClass);
@NgModule({ imports: [CommonModule, RouterModule], declarations: [decoratedCmp] })
class DynamicHtmlModule { }
return compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
.then((moduleWithComponentFactory: ModuleWithComponentFactories<any>) => {
return moduleWithComponentFactory.componentFactories.find(x => x.componentType === decoratedCmp);
});
}
感谢任何帮助。另外,如果您有其他解决问题的方法,请告诉我。
【问题讨论】:
-
我不确定,但您可以尝试:
@Component(metadata) class DynamicComponent {...}而不是尝试将课程保存在consts 中?基本上与您通常定义组件的方式相同 -
有帮助吗?
-
可以直接设置组件的属性
标签: angular templates input dynamic