【问题标题】:How to provide @Input when rendering dynamic template in Angular 2在Angular 2中渲染动态模板时如何提供@Input
【发布时间】: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


【解决方案1】:

我怀疑这对你有用:

@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

【讨论】:

  • 按照建议,@Injectable 装饰器丢失了。现在很好用!
猜你喜欢
  • 2017-03-12
  • 1970-01-01
  • 1970-01-01
  • 2020-05-12
  • 1970-01-01
  • 2020-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多