簡體   English   中英

如何在ES6中使用angular2 DynamicComponentLoader?

[英]How to use angular2 DynamicComponentLoader in ES6?

沒有使用打字稿而是使用ES6和angular2 alpha39動態加載組件。 以下代碼與我在我的應用程序中的代碼類似。 我注意到的是angular2不會創建DynamicComponentLoaderElementRef的實例並注入構造函數。 他們是未定義的。

如何使用ES6和angular2 alpha39注入DynamicComponentLoader?

import {Component, View, Inject, DynamicComponentLoader, ElementRef } from 'angular2/angular2'

@Component({
  selector: 'dc',
  bindings: [ DynamicComponentLoader ]
})
@View({
  template: '<b>Some template</b>'
})

class DynamicComponent {}

@Component({
  selector: 'my-app'
})
@View({
  template: '<div #container></div>'
})
@Inject(DynamicComponentLoader)
@Inject(ElementRef)
export class App {
  constructor(
    dynamicComponentLoader, 
    elementRef
  ) {
    dynamicComponentLoader.loadIntoLocation(DynamicComponent, elementRef, 'container');
  }
}

如果你想在ES7中編寫代碼,我認為目前最簡潔的注入方法是使用靜態getter parameters

import {Component, View, DynamicComponentLoader, ElementRef } from 'angular2/angular2'

@Component({
  selector: 'my-app'
})
@View({
  template: '<div #container></b>'
})
export class App {

  static get parameters() {
    return [[DynamicComponentLoader], [ElementRef]];  
  }

  constructor(dynamicComponentLoader, elementRef) {
    dynamicComponentLoader.loadIntoLocation(DynamicComponent, elementRef, 'container');
  }
}

看到這個plunker

如果要在ES6中編寫代碼(不支持裝飾器),則還必須使用靜態getter作為annotations屬性。 在這種情況下,您必須導入ComponentMetadataViewMetadata而不是ComponentView例如:

import {ComponentMetadata, ViewMetadata, DynamicComponentLoader, ElementRef } from 'angular2/angular2';

export class App {

  static get annotations() {
    return [
      new ComponentMetadata({
        selector: 'app'
      }),
      new ViewMetadata({
        template: '<div #container></b>'
      })
    ];
  }

  static get parameters() {
    return [[DynamicComponentLoader],[ElementRef]];  
  }

  constructor(dynamicComponentLoader, elementRef) {
    dynamicComponentLoader.loadIntoLocation(DynamicComponent, elementRef, 'container');
  }
}

看到這個plunker

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM