动态更改Angular 4组件的模板
使用Angular 4.1,我试图在模块渲染之前动态更改模块类型的模板.这可能吗?
我们在页面上引导未知数量的组件(来自已知的组件类型列表),并且页面可能包含多个相同类型的组件.我发现了一种方法可以为每个组件提供一个不同的选择器,这样它们就可以单独渲染(即使它们属于同一类型),但我还需要给每个组件一个不同的模板.模板应该是所选元素的内部HTML. 这是代码: import { Component,NgModule,Inject,ApplicationRef,ComponentFactoryResolver,OpaqueToken,Type } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { MyNavComponent } from './MyNav.component'; import { MyRotatorComponent } from './MyRotator.component'; import { MySignUpComponent } from './MySignUp.component'; export const BOOTSTRAP_COMPONENTS_TOKEN = new OpaqueToken('bootstrap_components'); @NgModule({ imports: [BrowserModule],declarations: [ MyNavComponent,MyRotatorComponent,MySignUpComponent ],entryComponents: [ MyNavComponent,providers: [ { provide: BOOTSTRAP_COMPONENTS_TOKEN,useValue: [ { type: MyNavComponent },{ type: MyRotatorComponent },{ type: MySignUpComponent } ] },] }) export class AppModule { constructor( private resolver: ComponentFactoryResolver,@Inject(BOOTSTRAP_COMPONENTS_TOKEN) private components: [Component],) { } ngDoBootstrap(appRef: ApplicationRef) { console.log(this.components); this.components.forEach((componentDef: { type: Type<any>,selector: string }) => { const factory = this.resolver.resolveComponentFactory(componentDef.type); let selector = factory.selector; let nodes = document.querySelectorAll(selector); for (let i = 0; i < nodes.length; i++) { let node = nodes[i]; (<any>factory).factory.selector = node; //The next line doesn't work... how can I dynamically set the template? (<any>factory).factory.template = node.innerHTML; appRef.bootstrap(factory); } }); } } 如上面代码末尾所述,(< any> factory).factory.template = node.innerHTML;不起作用.我也尝试修改该类型的元数据,但这也不起作用. 我想通过其他方式实现什么?如果没有,这是否值得提交作为功能请求? (注意:上面的代码部分基于https://github.com/angular/angular/issues/7136的其他代码.) 更新: 我想知道在将来的Angular更新中,我是否能够通过将模板设置为< ng-content>< / ng-content>来实现相同的结果.包括所选元素的innerHTML.现在使用自举组件是不可能的,但基于这个issue on Git,我希望它很快就能实现.
创建后,无法为组件工厂设置模板. Angular编译器在生成工厂时解析模板,并为每个组件创建视图类.创建组件工厂及其视图类后,您无法修改它.在您的示例中,您使用的是ComponentFactoryResolver
const factory = this.resolver.resolveComponentFactory(componentDef.type); 返回已创建的工厂. 唯一的选择是在编译器生成工厂之前更改模板.但我不认为这是可能的.您可能需要查看动态生成的组件. 阅读Here is what you need to know about dynamic components in Angular以获取更多信息. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |