如何在Angular 2中渲染动态模板时提​​供@Input

时间:2017-04-14 21:07:21

标签: angular templates input dynamic

我试图在运行时动态加载模板,渲染它并绑定到模板中的动态数据。

在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);
  });
}

感谢任何帮助。如果您有其他方法可以解决问题,请告诉我。

1 个答案:

答案 0 :(得分:0)

我怀疑这对你有用:

@Injectable()
class DynamicComponent {
  data: any;

  constructor(private injector: Injector) {
    this.data = this.injector.get('data');
  }
}

export function createComponentFactory(compiler: Compiler, metadata: Component): Promise<ComponentFactory<any>> {
    const decoratedCmp = Component(metadata)(DynamicComponent);

    @NgModule({ imports: [CommonModule, RouterModule, SharedModule], declarations: [decoratedCmp] })
    class DynamicHtmlModule { }

    compiler.clearCacheFor(decoratedCmp);
    return compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
       .then((moduleWithComponentFactory: ModuleWithComponentFactories<any>) => {
        return moduleWithComponentFactory.componentFactories.find(x => x.componentType === decoratedCmp);
      });
}

<强> Plunker Example