Angular 2.1.0动态创建子组件

Srl*_*rle 10 javascript angular

我正在尝试做的angular 2.1.0是动态创建应该注入父组件的子组件.例如父组件是lessonDetails包含用于所有课程如像按钮共享的东西Go to previous lesson,Go to next lesson和其他东西.基于路径参数,应该是子组件的课程内容需要动态注入父组件.子组件的HTML(课程内容)在外面的某处定义为普通字符串,它可以是以下对象:

export const LESSONS = {
  "lesson-1": `<p> lesson 1 </p>`,
  "lesson-2": `<p> lesson 2 </p>`
}
Run Code Online (Sandbox Code Playgroud)

通过innerHtml父组件模板中使用类似的内容,可以轻松解决问题.

<div [innerHTML]="lessonContent"></div>
Run Code Online (Sandbox Code Playgroud)

在路径参数的每次更改的情况下lessonContent,父组件的属性将改变(将从LESSON对象获取内容(新模板)),从而导致更新父组件模板.这有效,但角度不会处理通过注入的内容,innerHtml因此无法使用routerLink和其他东西.

在新的角度释放之前,我使用来自http://blog.lacolaco.net/post/dynamic-component-creation-in-angular-2/的解决方案解决了这个问题,我一直在使用ComponentMetadataComponentResolver来动态创建子组件, 喜欢:

const metadata = new ComponentMetadata({
  template: this.templateString,
});
Run Code Online (Sandbox Code Playgroud)

templateString传递给子组件的Input属性为子组件.双方MetaDataComponentResolver已被弃用/去掉angular 2.1.0.

所以问题不仅仅是关于动态组件创建,如在少数相关的SO问题中描述的那样,如果我为每个课程内容定义了组件,问题将更容易解决.这意味着我需要为100个不同的课程预先声明100个不同的组件.不推荐使用的元数据提供的行为类似于在单个组件的运行时更新模板(在路径参数更改时创建和销毁单个组件).

更新1:在最近的角度版本中,需要在entryComponents内部预定义需要动态创建/注入的所有组件@NgModule.因此,在我看来,与上述问题相关,如果我需要100课(需要动态创建的组件),这意味着我需要预定义100个组件

更新2:基于更新1,可以通过ViewContainerRef.createComponent()以下方式完成:

// lessons.ts
@Component({ template: html string loaded from somewhere })
class LESSON_1 {}

@Component({ template: html string loaded from somewhere })
class LESSON_2 {}

// exported value to be used in entryComponents in @NgModule
export const LESSON_CONTENT_COMPONENTS = [ LESSON_1, LESSON_2 ]
Run Code Online (Sandbox Code Playgroud)

现在在路线参数的父组件中更改

const key = // determine lesson name from route params

/**
 * class is just buzzword for function
 * find Component by name (LESSON_1 for example)
 * here name is property of function (class)
 */

const dynamicComponent = _.find(LESSON_CONTENT_COMPONENTS, { name: key });
const lessonContentFactory = this.resolver.resolveComponentFactory(dynamicComponent);
this.componentRef = this.lessonContent.createComponent(lessonContentFactory);
Run Code Online (Sandbox Code Playgroud)

父模板看起来像:

<div *ngIf="something" #lessonContentContainer></div>
Run Code Online (Sandbox Code Playgroud)

lessonContentContainer装饰@ViewChildren属性在哪里lessonContent装饰,@ViewChild并初始化ngAfterViewInit ()为:

ngAfterViewInit () {
  this.lessonContentContainer.changes.subscribe((items) => {
    this.lessonContent = items.first;
    this.subscription = this.activatedRoute.params.subscribe((params) => {
      // logic that needs to show lessons
    })
  })
}
Run Code Online (Sandbox Code Playgroud)

解决方案有一个缺点,即需要预定义所有组件(LESSON_CONTENT_COMPONENTS).
有没有办法使用单个组件并在运行时更改该组件的模板(在路径参数更改)?

yur*_*zui 14

您可以使用以下HtmlOutlet指令:

import {
  Component,
  Directive,
  NgModule,
  Input,
  ViewContainerRef,
  Compiler,
  ComponentFactory,
  ModuleWithComponentFactories,
  ComponentRef,
  ReflectiveInjector
} from '@angular/core';

import { RouterModule }  from '@angular/router';
import { CommonModule } from '@angular/common';

export function createComponentFactory(compiler: Compiler, metadata: Component): Promise<ComponentFactory<any>> {
    const cmpClass = class DynamicComponent {};
    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);
      });
}

@Directive({ selector: 'html-outlet' })
export class HtmlOutlet {
  @Input() html: string;
  cmpRef: ComponentRef<any>;

  constructor(private vcRef: ViewContainerRef, private compiler: Compiler) { }

  ngOnChanges() {
    const html = this.html;
    if (!html) return;

    if(this.cmpRef) {
      this.cmpRef.destroy();
    }

    const compMetadata = new Component({
        selector: 'dynamic-html',
        template: this.html,
    });

    createComponentFactory(this.compiler, compMetadata)
      .then(factory => {
        const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);   
        this.cmpRef = this.vcRef.createComponent(factory, 0, injector, []);
      });
  }

  ngOnDestroy() {
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }    
  }
}
Run Code Online (Sandbox Code Playgroud)

另见Plunker示例

自定义组件的示例

对于AOT编译,请参阅这些主题

另请参阅github Webpack AOT示例 https://github.com/alexzuza/angular2-build-examples/tree/master/ngc-webpack