我试图动态创建用于报告的组件,这就是我从此链接获得的教程:
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>
创建动态组件的提示
@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
我忘记了什么吗? 我很乐意提供帮助。
答案 0 :(得分:1)
您正在更改this.testing
的值并显示data.testing
,因此看来constructor
和ngOnInit
无效,因此如果要显示{{1} }试试这个:
this.testing