【发布时间】:2020-01-16 22:04:29
【问题描述】:
我尝试为报告创建动态组件,这是我从这个链接获得的教程:
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>
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"
}
}
服务
@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
我是不是忘记了什么? 我很乐意提供任何帮助。
【问题讨论】:
-
data.testing 和你 ts 中的测试不一样吗?
-
@Ramesh:谢谢...那一定是测试...我的错误...