在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML5  HTML/ Angular的ComponentFactory創(chuàng)建Component的時(shí)候怎么

Angular的ComponentFactory創(chuàng)建Component的時(shí)候怎么對Component的構(gòu)造函數(shù)注入?yún)?shù)呢?

題目描述

我想用Angular的ComponentFactoryResolver動(dòng)態(tài)創(chuàng)建一個(gè)Component然后追加到body里面,下面是我的實(shí)現(xiàn)步驟

// modal.component.js
import { Component, ViewChild, ViewContainerRef } from '@angular/core';

@Component({
  selector: 'modal',
  template: `<p>modal works! </p>`,
})
export class ModalComponent {

  constructor(
      options: ModalOptions) {
    console.log(options);
  }

}

export class ModalOptions {
  title: string;
  content: string;
}
// modal.service.js

// ...import
@Injectable({
  providedIn: 'root',
})
export class ModalService {
  
  // ...constructor

  public create(options: ModalOptions) {
    let componentFactory = this.resolver.resolveComponentFactory(ModalComponent);
    let injector = Injector.create([
      {
        provide: ModalOptions,
        useValue: options,
      },
    ]);
    let componentRef = componentFactory.create(injector);
    let componentRootNode = (componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;
    this.container.appendChild(componentRootNode);
    return componentRef;
  }

}

上面的代碼在運(yùn)行的時(shí)候會(huì)報(bào)錯(cuò),錯(cuò)誤信息如下

ERROR Error: Uncaught (in promise): Error: Can't resolve all parameters for ModalComponent: (?).
Error: Can't resolve all parameters for ModalComponent: (?).

請問是我注入?yún)?shù)的方式不對么?應(yīng)該怎么對動(dòng)態(tài)創(chuàng)建的Component的構(gòu)造函數(shù)注入?yún)?shù)么?

謝謝!

回答
編輯回答
逗婦惱

ModalComponent構(gòu)造參數(shù)中要寫修飾符如publicprivate、readonly等等。這樣才會(huì)自動(dòng)構(gòu)造屬性并創(chuàng)建。

constructor(
      public options: ModalOptions
) {
    console.log(options);
}
2017年4月21日 03:34
編輯回答
吢丕

樓上說的不對,正解應(yīng)當(dāng)是這樣的,把 ModalOptions 的聲明移動(dòng)到 ModalComponent 之前,比如:

export class ModalOptions {
  title: string;
  content: string;
}

@Component({
  selector: 'modal',
  template: `<p>modal works! </p>`,
})
export class ModalComponent {

  constructor(
    options: ModalOptions) {
  }

}

關(guān)于原因呢,可以看這里,如果你非要先聲明組件的話,也可以使用 forwardRef() 來解決,這個(gè)網(wǎng)上查查就有,我就不細(xì)說了,但是還是建議你遵循 Angular 中提倡的 one class one file 原則。

2017年7月14日 14:30