动态组件加载器Angular2 final

时间:2016-10-05 08:38:20

标签: angular ionic2

我试图像这样创建一个动态组件:

这是我的文件dynamicComponent.ts:

import {Directive, Input, ViewContainerRef, Component, ReflectiveInjector, ComponentFactory, ComponentFactoryResolver} from '@angular/core';

export function createComponentFactory(resolver: ComponentFactoryResolver, metadata: Component): Promise<ComponentFactory<any>> {
const cmpClass = class DynamicComponent {
};
const decoratedCmp = Component(metadata)(cmpClass);
return new Promise((resolve) => {
    resolve(resolver.resolveComponentFactory(decoratedCmp)); 
});
}

@Directive({
selector: 'dynamic-html-outlet'
 })
export class DynamicComponent {
@Input() src: string;

constructor(public vcRef: ViewContainerRef, public resolver:    ComponentFactoryResolver) {
}

ngOnChanges() {
    if (!this.src) return;

    const metadata = new Component({
        selector: 'dynamic-component',
        template: this.src
    });
    createComponentFactory(this.resolver, metadata)
        .then(factory => {
            const injector = ReflectiveInjector.fromResolvedProviders([],    this.vcRef.parentInjector);
            this.vcRef.createComponent(factory, 0, injector, []).changeDetectorRef.detectChanges();
        });
}
}

这是app.module.ts:

@NgModule({
   declarations: [
   MyApp,
   DynamicComponent,
   ...APP_PAGES,
   ...APP_DIRECTIVES 
],
imports: [
  IonicModule.forRoot(MyApp),
  NgReduxModule,
  MomentModule,
  TranslateModule.forRoot({
   provide: TranslateLoader,
   useFactory: (http: Http) => new TranslateStaticLoader(http, '../assets/i18n', '.json'),
  deps: [Http]
   })
  ],
 bootstrap: [IonicApp],
 entryComponents: [
 MyApp,
 //DynamicComponent,
 //ScrollableHeader,
 AppLink, 
 ...APP_PAGES,
 ...APP_DIRECTIVES
 ],
 providers: [
  ...APP_SERVICES
 ]
 })

必须加载的组件 AppLink 定义如下:

@Component({
  selector: 'app-link',
  template: '<a (click)="openLink($event);"><ng-content></ng-content></a>',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppLink {
  @Input() link;
  //some method here
}

我总是遇到这个错误:

polyfills.js:3未处理的Promise拒绝:模板解析错误: 无法绑定到&#39;链接&#39;因为它不是app-link&#39;的已知属性。

感谢您的帮助吗?

1 个答案:

答案 0 :(得分:0)

您需要将组件添加到

@NgModule({
  entryComponents: [MyDynamicComponent],
  ...
})

正在创建组件工厂。