angular dart: is it possible to inject a component?

Issue

dart 1.24.3, Angular 4.0.0

For reusable reasons, I have divided my application into many packages.
Let’s say that I’m using package C, that depends on package B that depends on package A. A is used also in other packages, and B can be used stand-alone.
Finally, C add some more info to B and it is in some way customized.

Now, in package A I have a modal window that shows some info, but in package B I should add a component and in package C even one more.
As this modal window is used in all my component forms, I cannot customize it inside the child packages, because this would mean to inherit all parent forms and customize them.
What I would like to use is something like the providers injection (example what I would like to declare in my application component in Package C):

 ModalWindowComponent,
      const Provider(pack_b.ModalWindowComponent, useClass: ModalWindowComponent),
      const Provider(pack_a.ModalWindowComponent, useClass: ModalWindowComponent)

Googling I have seen something that maybe I can use in my case, the ComponentResolver class. But I could not get if it is something new to Angular 5 or can be used also in angular 4. In some other places it seems also that it will be deprecated, so I’m a little bit confused.
More, I do not need to dynamically add a component in the DOM, but dynamically substitute the component with the one (that inherits the base one) from the child package.

Is there a way to do that? Is there some example that I can give a look at?

Solution

You can use ComponentLoader
which requires passing the ComponentFactory and a place in the DOM. There are good examples in methods’ documentation.

You get the ComponentFactory for the Component by importing the .template.dart file which has @Component annotation, and appending NgFactory to the name of the component, for example:

file foo.dart:

@Component(selector: 'foo')
class FooComponent {}

file 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);
  }
}

Answered By – rkj

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *