ngoninit не работает с динамическим компонентом

Я попытался создать динамический компонент для отчетности, который я получил по этой ссылке:

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

Динамический компонент уже загружен, но ngOnInit не работает, у меня было много проводников, например:

Но до сих пор не решить мою проблему.

Вот мой код:

класс элемента

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

интерфейс

export interface ReportComponent {
    data: any;
  }

директива

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

html

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

ts для создания динамического компонента

@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(); 
   }
}

Код для динамического компонента:

HTML

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

ТС

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"
  }
}

услуги

@Injectable()

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

    return lsReport[reportName];
  }
}

Навигация по маршруту

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

Результат, когда я вызываю компонент:

введите здесь описание изображения

Результат должен быть:

//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

Я что-то забыл? Буду рад любой помощи.


person Hans    schedule 16.09.2019    source источник
comment
разве data.testing не отличается от тестирования в вашем ts?   -  person Ramesh Reddy    schedule 16.09.2019
comment
@Ramesh: Спасибо... это должно быть проверка... моя ошибка...   -  person Hans    schedule 16.09.2019


Ответы (1)


Вы меняете значение this.testing и отображаете data.testing, поэтому вам кажется, что constructor и ngOnInit не работают, поэтому, если вы хотите отобразить this.testing, попробуйте следующее:

<div>
    Test :  {{data.test}} Testing : {{testing}}
</div>
person Mustahsan    schedule 16.09.2019