Kir*_*ver 8 angular2-template angular2-components angular
使用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,
MyRotatorComponent,
MySignUpComponent
],
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);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
如上面代码末尾附近所述,(<any>factory).factory.template = node.innerHTML;不起作用.我也尝试修改该类型的元数据,但这也不起作用.
我想通过其他方式实现什么?如果没有,这是否值得提交作为功能请求?
(注意:以上代码部分基于https://github.com/angular/angular/issues/7136上的其他代码.)
我想知道在将来的Angular更新中,我是否能够通过将模板设置<ng-content></ng-content>为包含所选元素的innerHTML 来实现相同的结果.现在使用自举组件是不可能的,但基于Git上的这个问题,我希望它很快就会出现.
创建组件工厂后,您无法为其设置模板。Angular编译器在生成工厂时会解析模板,并为每个组件创建一个视图类。创建组件工厂及其视图类之后,您将无法对其进行修改。在您的示例中,您正在使用ComponentFactoryResolver
const factory = this.resolver.resolveComponentFactory(componentDef.type);
Run Code Online (Sandbox Code Playgroud)
返回已创建的工厂。
唯一的选择是在编译器生成工厂之前更改模板。但是我认为这是不可能的。您可能必须看一下组件的动态生成。
阅读 这里是您需要了解的有关Angular中动态组件的信息,以获取更多信息。
| 归档时间: |
|
| 查看次数: |
18355 次 |
| 最近记录: |