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

Angular的ComponentFactory創(chuàng)建Component的時候怎么對Component的構造函數注入參數呢?

題目描述

我想用Angular的ComponentFactoryResolver動態(tài)創(chuàng)建一個Component然后追加到body里面,下面是我的實現(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;
  }

}

上面的代碼在運行的時候會報錯,錯誤信息如下

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

請問是我注入參數的方式不對么?應該怎么對動態(tài)創(chuàng)建的Component的構造函數注入參數么?

謝謝!

回答
編輯回答
逗婦惱

ModalComponent構造參數中要寫修飾符如public、private、readonly等等。這樣才會自動構造屬性并創(chuàng)建。

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

樓上說的不對,正解應當是這樣的,把 ModalOptions 的聲明移動到 ModalComponent 之前,比如:

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

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

  constructor(
    options: ModalOptions) {
  }

}

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

2017年7月14日 14:30