ng-docs.github.io
ng-docs.github.io copied to clipboard
动态创建组件如何在动态创建的组件上增加指令.
正常情况下
<app-xxx addColor></app-xxx>
这样添加一个addColor指令是没问题的, 但是到动态创建这里,问题就多 了,
this.componentFactory = componentFactoryResolver.resolveComponentFactory(component)
this.anchor.createComponent(this.componentFactory)
可以手动指定注入器,映射内容,插入位置,导入模块,但是就没说,如何增加指令,查了挺多文档,但是都没说如何实现,是不是动态添加的无法实现这个
- 问题转化了下,如何动态的添加指令到其他的标签上,毕竟要先能动态添加才有可能在动态组件上动态添加.....结果,也没有
- 目前十分尴尬,还没有找到有效的方法.唯一可行的就是在组件内部增加一个标签,把指令绑定到标签上,但是感觉又是很Low,白白的增加了一层标签,强迫症心里不能满足....
解决方案
坑爹预警,只能用于jit,aot会报错
把组件和模块的类动态生成,虽然能实现,但是........如果你真的必须要使用这个,再考虑这个方案吧,毕竟是非正规方案 动态添加好像我遇到的项目都几乎很少使用,优点就是确实能动态加载哪些组件,当你组件太多没法全搞进去的时候,,跟html拼模板一样,缺点我猜测,应该不能享受到aot了,毕竟你是根据参数来了
async load(moduleFn: () => Promise<Type<DynamicEntryPoint>>) {
/**模块的类 */
let module = await moduleFn()
/**载入的模块工厂 */
const ngModuleFactory = await this.compiler.compileModuleAsync(module)
const ngModuleRef = ngModuleFactory.create(this.injector)
const selector = this.selector || getSelector(ngModuleRef);
//doc 通过拼字符串实现动态指令
const template = `<${selector} ${this.inputStr} ${this.outputStr} ${this.ngModelStr} #dynamicComponent></${selector}>`
/**自定义组件部分 */
@Component({
template: template,
})
class TemplateComponent {
}
const imports = [module]
//doc 注意这里的模块可以加入指令(传入的变量),然后在上面的组件中加入
@NgModule({ declarations: [TemplateComponent], imports: imports })
class TemplateModule {
}
/**编译模块 */
const mod = this.compiler.compileModuleAndAllComponentsSync(TemplateModule);
/**组件工厂 */
const factory: ComponentFactory<TemplateComponent> = mod.componentFactories.find((comp) => comp.componentType === TemplateComponent);
/**通过锚点创建组件 */
this.componentRef = this.anchor.createComponent(factory, undefined, this.injector, undefined, ngModuleRef);
}
@asnowwolf