Search code examples
angularngoninit

ngoninit not working on dynamically component


I tried to created dynamically component for reporting, which is i got the tutorial from this link :

https://angular.io/guide/dynamic-component-loader

Dynamic component is already load, but ngOnInit is not working, i had explorer many way such as :

But still not solve my problem.

Here is my code :

item class

export class ReportItem {
  constructor(public component: Type<any>, public data: any) {}
}

inteface

export interface ReportComponent {
    data: any;
  }

directive

@Directive({
  selector: '[reporting]',
})
export class ReportDirective {
  constructor(public viewContainerRef: ViewContainerRef) { }
}

html

<section id="reporting-contener">
  <ng-template reporting></ng-template>
</section>

ts to create dynamic component

@Component({
  selector: 'app-reporting',
  templateUrl: './reporting.component.html',
  styleUrls: ['./reporting.component.scss']
})
export class ReportingComponent implements OnInit {
 reports: ReportItem = null;
  @ViewChild(ReportDirective) reportHost: ReportDirective;
  backTo:Boolean = false;
  reportName:string = ""
  constructor(
    private route: ActivatedRoute,
    private router:Router,
    private componentFactoryResolver: ComponentFactoryResolver,
    private reportservice:ReportService,
    private gm:GeneralMethod,
  ) { 

    this.route.params.subscribe(params => {
      this.reportName = params['reportName']
      this.reports = this.reportservice.getReports(this.reportName);
      this.route.queryParams.subscribe(params => {
        if(!this.gm.isObjectEmpty(params)){

          this.reports.data= params;

        }else{

          this.backTo = true;
        }
      });

    });

  }
  componentRef = null
  ngOnInit(){
    if(this.backTo ){
      //this.router.navigate["transaction"]
    }

    const reportItem = this.reports;

    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(reportItem.component);
    const viewContainerRef = this.reportHost.viewContainerRef;
    viewContainerRef.clear();
    this.componentRef = viewContainerRef.createComponent(componentFactory);
    (<ReportComponent>this.componentRef.instance).data = reportItem.data;
    this.componentRef.changeDetectorRef.detectChanges();
  }
  ngOnDestroy() {
    this.componentRef.destroy(); 
   }
}

Code for dynamic component :

HTML

<div>
    Test :  {{data.test}} Testing : {{data.testing}}
</div>

ts

export class ReportingTesting implements ReportComponent, OnInit, AfterViewInit {
  @Input() data: any;

  testing = "100" //not working
  constructor(){ //not working
    this.testing = "Test call on constructor"
  }
  ngOnInit(){ //not working
    this.testing = "Test call on ngoninit"
  }
  ngAfterViewInit(){ //not working
    this.testing = "Test call on ngAfterViewInit"
  }
}

services

@Injectable()

export class ReportService {
  getReports(reportName:string) {
    let lsReport = [];
    lsReport["test"] = new ReportItem(ReportingTesting, {});

    return lsReport[reportName];
  }
}

Route navigate

this.router.navigate(['/report/test'], { queryParams: {'test':"Test Param", route:""}});

The Result when i call the component :

enter image description here

Result should be :

//constructor
Test : Test Param Testing : Test call on constructor

//ngOnInit
Test : Test Param Testing : Test call on ngoninit

//ngAfterViewInit
Test : Test Param Testing : Test call on ngAfterViewInit

Am I forgot something? I would be glad for any help.


Solution

  • You are changing value of this.testing and displaying data.testing so it appears to you that constructor and ngOnInit are not working so if you want to display this.testing try this:

    <div>
        Test :  {{data.test}} Testing : {{testing}}
    </div>