Angular 2の$compileに相当する質問

Angular 2の$compileに相当する質問

ディレクティブを含む HTML を手動でコンパイルしたいのですが、$compileAngular 2 で同等のものは何ですか?

たとえば、Angular 1 では、HTML のフラグメントを動的にコンパイルして DOM に追加できました。

var e = angular.element('<div directive></div>');
element.append(e);
$compile(e)($scope);

ベストアンサー1

角度2.3.0(2016-12-07)

すべての詳細を確認するには、以下を確認してください。

実際に動作を確認するには:

校長:

1) テンプレートを作成する
2) コンポーネントを作成する
3) モジュールを作成する
4) モジュールをコンパイルする
5) ComponentFactory を作成 (およびキャッシュする)
6) Target を使用してそのインスタンスを作成する

コンポーネントの作成方法の簡単な概要

createNewComponent (tmpl:string) {
  @Component({
      selector: 'dynamic-component',
      template: tmpl,
  })
  class CustomDynamicComponent  implements IHaveDynamicData {
      @Input()  public entity: any;
  };
  // a component for this particular template
  return CustomDynamicComponent;
}

NgModuleにコンポーネントを注入する方法

createComponentModule (componentType: any) {
  @NgModule({
    imports: [
      PartsModule, // there are 'text-editor', 'string-editor'...
    ],
    declarations: [
      componentType
    ],
  })
  class RuntimeComponentModule
  {
  }
  // a module for just this Type
  return RuntimeComponentModule;
}

コードスニペットの作成方法ComponentFactory (そしてそれをキャッシュする)

public createComponentFactory(template: string)
    : Promise<ComponentFactory<IHaveDynamicData>> {    
    let factory = this._cacheOfFactories[template];

    if (factory) {
        console.log("Module and Type are returned from cache")

        return new Promise((resolve) => {
            resolve(factory);
        });
    }

    // unknown template ... let's create a Type for it
    let type   = this.createNewComponent(template);
    let module = this.createComponentModule(type);

    return new Promise((resolve) => {
        this.compiler
            .compileModuleAndAllComponentsAsync(module)
            .then((moduleWithFactories) =>
            {
                factory = _.find(moduleWithFactories.componentFactories
                                , { componentType: type });

                this._cacheOfFactories[template] = factory;

                resolve(factory);
            });
    });
}

上記の結果を使用する方法を示すコードスニペット

  // here we get Factory (just compiled or from cache)
  this.typeBuilder
      .createComponentFactory(template)
      .then((factory: ComponentFactory<IHaveDynamicData>) =>
    {
        // Target will instantiate and inject component (we'll keep reference to it)
        this.componentRef = this
            .dynamicComponentTarget
            .createComponent(factory);

        // let's inject @Inputs to component instance
        let component = this.componentRef.instance;

        component.entity = this.entity;
        //...
    });

詳細を全て記載した完全な説明こちらで読む、または観察する実例

廃止 - Angular 2.0 RC5 関連 (RC5 のみ)

以前のRCバージョンのソリューションを見るには、検索してください。この投稿の履歴

おすすめ記事