角镖:是否可以注入一个组件?

J F*_*J F 0 dart angular-dart angular

dart 1.24.3,Angular 4.0.0

出于可重复使用的原因,我将我的应用程序分成了许多包.假设我使用的是包C,这取决于依赖于包A的包B.在其他包中也使用A,B可以单独使用.最后,C向B添加了更多信息,并以某种方式定制.

现在,在包中AI有一个显示一些信息的模态窗口,但在包中BI应该添加一个组件,在包C中再添加一个.由于这个模态窗口在我的所有组件表单中使用,我无法在子包内自定义它,因为这意味着继承所有父表单并自定义它们.我想要使​​用的是类似于提供者注入(例如我想在我的应用程序组件C中声明的内容):

 ModalWindowComponent,
      const Provider(pack_b.ModalWindowComponent, useClass: ModalWindowComponent),
      const Provider(pack_a.ModalWindowComponent, useClass: ModalWindowComponent)
Run Code Online (Sandbox Code Playgroud)

谷歌搜索我看到了一些我可以在我的案例中使用的东西,即ComponentResolver类.但是,如果它是Angular 5的新功能或者也可以在角度4中使用,我无法得到.在其他一些地方它似乎也会被弃用,所以我有点困惑.此外,我不需要在DOM中动态添加组件,而是动态地将组件替换为子包中的组件(继承基础组件).

有没有办法做到这一点?有什么例子我可以看看吗?

rkj*_*rkj 5

您可以使用ComponentLoader ,它需要ComponentFactory在DOM中传递和放置一个位置.方法文档中有很好的例子.

你得到了ComponentFactory通过导入的组件.template.dart其文件的@Component注释,并追加NgFactory到组件的名称,例如:

档案foo.dart:

@Component(selector: 'foo')
class FooComponent {}
Run Code Online (Sandbox Code Playgroud)

档案bar.dart:

import 'foo.template.dart';

@Component(selector: 'bar', template: '<div #placeholder></div>')
class BarComponent {
  final ComponentLoader _loader;

  @ViewChild('placeholder', read: ViewContainerRef)
  ViewContainerRef theDiv;

  BarComponent(this._loader);

  void load() {
    _loader.loadNextToLocation(FooComponentNgFactory, theDiv);
  }
}
Run Code Online (Sandbox Code Playgroud)