Search code examples
angularangular8

How to inject an array of a class through Injector.create


I've a component:

export class PhotoComponent implements OnInit {
 constructor(private foo:Foo[]) { 
      console.log(this.foo);
    }
}

I am trying to dynamically render this component in a parent Component like below:

export class AlbumComponent implements OnInit {

  //_ctr definition and other not relevant code


  dynamicComponent:any = PhotoComponent
  injector:any = createInjector(this.foolist);
  createInjector(foolist) {
    let injector = Injector.create([
      { provide: Foo, useClass: Foo, useValue: foolist, multi:true}
    ], this.injector);
    return injector;
  }
}

and in album.component.html:

<ng-container *ngComponentOutlet="dynamicComponent;injector:injector"> </ng-container>

this all works if Foo is a not an array. So how should I inject an array?


Solution

  • I was able to solve my problem.

    Concept:

    so basically Angular Injector creates instance of a given class, but needs a provider to tell it how to create that class. Also, while doing so, you get to specify what value should it have. So instead of expecting the Injector to create array of an instance, I just created a bigger wrapper class having my values and it worked i.e.:

    • created new wrapper:

      @Injectable()
      export class WrapperClass {
          bar: Bar;
          foo: Foo[]
      }
      
    • and updated Injector creation like below:

      createInjector(bar, foo) {
          const wrapper: Wraper = { bar: bar, foo: foo };
          let injector = Injector.create([
            { provide: Wrapper, useClass: Wrapper, useValue: wrapper }
          ], this.injector);
          return injector;
       }
      
    • and updated component to be rendered dynamically like below:

      export class PhotoComponent implements OnInit {
           constructor(private wrapper:Wrapper) { 
                console.log(this.wrapper.foo);
            }
      }