Anil Jagtap
Anil Jagtap

Reputation: 1810

Angular 2 dynamic component not executing

I want to create and execute multiple dynamic component. I want to execute all the component which is present in list. If 3 components are available in list then only one component is executing which is present on last index.

I referred this code.

I'm checking in right.panel.ts file if this component's are present in list or not. If present then I'm calling particular component.

But, here the problem is only FreeMemoryComponent is calling from right.panel.ts, if have other component in list aslo. Here, not calling HeapMemoryComponent, DiskSpaceCOmponent, CpuUsageComponent.

App.module.ts

import.....

@NgModule({
declarations: [
 AppComponent,
 HeapMemoryComponent,
 DiskSpaceComponent,
 CpuUsageComponent,
 FreeMemoryComponent,
 BottomPanelDynamicComponent
],
imports: [
 BrowserModule,
 FormsModule,
 HttpModule,
 MaterialModule.forRoot(),
 DndModule.forRoot(),
 routing
],
providers: [.....],
bootstrap: [AppComponent],
entryComponents:[...],
exports: [...]
})
export class AppModule { }

I'm calling to components from following file.

right.panel.ts

import { Component, OnInit } from '@angular/core';
import {HeapMemoryComponent} from '../heap-memory-graph/heap-memory-graph.component';
import {DiskSpaceComponent} from '../disk-space-graph/disk-space-graph.component';
import {CpuUsageComponent} from '../cpu-usage-graph/cpu-usage-graph.component';
import {FreeMemoryComponent} from '../free-memory-graph/free-memory-graph.component';

@Component({
  selector: 'app-rightpanel',
  templateUrl: './rightpanel.component.html',
  styleUrls: ['./rightpanel.component.css']
})
export class RightpanelComponent implements OnInit {
componentData2 = null;
constructor(private savedWidgetService:GetSavedWidgetService) {}

ngOnInit() {
    this.service.getSavedWidget().subscribe(lst => {
      for (var v in lst) {
        if (lst[v].name == "Heap Memory") {
          this.componentData2 = {
            component: HeapMemoryComponent,
            inputs: {
              showNum: 0
            }
          };
        } else if (lst[v].name == "Disk Space") {
          this.componentData2 = {
            component: DiskSpaceComponent,
            inputs: {
              showNum: 0
            }
          };
        } else if (lst[v].name == "CPU Usage") {
          this.componentData2 = {
            component: CpuUsageComponent,
            inputs: {
              showNum: 0
            }
          };
        } else if (lst[v].name == "Free Memory") {
          this.componentData2 = {
            component: FreeMemoryComponent,
            inputs: {
              showNum: 0
            }
          };

        } 
      }
    }
    }
    }

right.panel.html

<app-bottompanel [componentData2]="componentData2" class="row"></app-bottompanel>

And in following file i'm creating and executing component dynamically.

import {Component, Input, ViewContainerRef, ViewChild, ReflectiveInjector, ComponentFactoryResolver} from '@angular/core';
import {HeapMemoryComponent} from '../heap-memory-graph/heap-memory.component';
import {DiskSpaceComponent} from '../disk-space-graph/disk-space.component';
import {CpuUsageComponent} from '../cpu-usage-graph/cpu-usage.component';
import {FreeMemoryComponent} from '../free-memory-graph/free-memory.component';

@Component({
  selector: 'app-bottompanel',
  entryComponents[HeapMemoryComponent,DiskSpaceComponent,CpuUsageComponent,FreeMemoryComponent],
  template: `<div #dynamicComponentContainer></div>`,
})
export default class BottomPanelDynamicComponent {
  currentComponent2 = null;

  @ViewChild('dynamicComponentContainer', { read: ViewContainerRef }) 
  dynamicComponentContainer: ViewContainerRef;

  // component: Class for the component you want to create
  // inputs: An object with key/value pairs mapped to input name/input value
@Input() set componentData2(data: {component: any, inputs: any }) {
if (!data) {
  return;
}

// Inputs need to be in the following format to be resolved properly
let inputProviders = Object.keys(data.inputs).map((inputName) => {return {provide: inputName, useValue: data.inputs[inputName]};});
let resolvedInputs = ReflectiveInjector.resolve(inputProviders);

// We create an injector out of the data we want to pass down and this components injector
let injector = ReflectiveInjector.fromResolvedProviders(resolvedInputs, this.dynamicComponentContainer.parentInjector);

// We create a factory out of the component we want to create
let factory = this.resolver.resolveComponentFactory(data.component);

// We create the component using the factory and the injector
let component = factory.create(injector);

// We insert the component into the dom container
this.dynamicComponentContainer.insert(component.hostView);

// We can destroy the old component is we like by calling destroy
if (this.currentComponent2) {
  //this.currentComponent.destroy();
}

this.currentComponent2 = component;
}

constructor(private resolver: ComponentFactoryResolver) {

}
}

What is happening here? Please help me.

Upvotes: 1

Views: 489

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657416

Change

componentData2 = null;

to

componentData2 = [];

and

      this.componentData2 = {
        component: HeapMemoryComponent,
        inputs: {
          showNum: 0
        }
      };

to

      this.componentData2.push({
        component: HeapMemoryComponent,
        inputs: {
          showNum: 0
        }
      });

and

<app-bottompanel [componentData2]="componentData2" class="row"></app-bottompanel>

to

<app-bottompanel *ngFor="let cd2 of componentData2" [componentData2]="cd2" class="row"></app-bottompanel>

Upvotes: 1

Related Questions