Angular: How to pass data in ngComponentOutlet through Injector

前端 未结 3 804
清酒与你
清酒与你 2021-01-20 10:02

I\'m trying to dynamically create and show component and i need to pass some data into it, so that it knows what to show.

Here is my code:

html part:

3条回答
  •  攒了一身酷
    2021-01-20 11:04

    Thanks to yuzui's comment I managed to get something working

    The full runnable code can be found on Stackblitz

    export class AppComponent  {
      name = 'Dynamic components in Angular 5';
      private injectors = {};
    
      constructor(private inj: Injector) {
      }
    
      get widgets() {
        return [
          {id: 1, widgetType:'child-component', settings: { showSecondLine: false} },
          {id: 2, widgetType:'child2-component', settings: { text: 'helloooooooooo'} },
          ];
      }
      
      getComponent(config: WidgetConfiguration) {
        switch (config.widgetType) {
          case 'child-component':
            return ChildComponent;
          case 'child2-component':
            return Child2Component;
        }
      }
    
       getInjector(config: WidgetConfiguration) {
        let inject = this.injectors[config.id];
        if (!inject) {
          inject = Injector.create([
            { provide: GeneralSettings, useValue: config.settings }
          ], this.inj);
          this.injectors[config.id] = inject;
        }
    
        return inject;
      }
    }

提交回复
热议问题