我有一个动态组件加载器,我需要通过服务传入数据。click
例如,如果我启动该功能,我可以获得要显示的数据,但不是OnInit
.
- 我试过使用 AfterViewInit
- 最终数据将来自 API
更新: 工作StackBlitz
app.component.html
<app-answer-set></app-answer-set>
header.component.html
<ng-template appHeaderHost></ng-template>
header.component.ts
export class HeaderComponent implements OnInit {
@Input() component;
@ViewChild(HeaderHostDirective) headerHost: HeaderHostDirective;
constructor(private componentFactoryResolver: ComponentFactoryResolver) { }
ngOnInit() {
this.loadComponent();
}
loadComponent() {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.component);
const viewContainerRef = this.headerHost.viewContainerRef;
viewContainerRef.createComponent(componentFactory);
}
}
标头-host.directive.ts
export class HeaderHostDirective {
constructor(public viewContainerRef: ViewContainerRef) { }
}
标头数据.service.ts
export class HeaderDataService {
private headerDataSource = new Subject<any>();
headerData$ = this.headerDataSource.asObservable();
constructor() { }
setHeaderData(data: any) {
this.headerDataSource.next(data);
}
}
answer-set.component.html
<app-header [component]="component"></app-header>
<button (click)="setHeaderData()">click</button>
answer-set.component.ts
export class AnswerSetComponent implements OnInit {
component: any = AnswerSetHeaderDetailsComponent;
constructor(private headerDataService: HeaderDataService) { }
ngOnInit() {
this.setHeaderData();
}
setHeaderData() {
const data = [{name: 'Header stuff'}];
this.headerDataService.setHeaderData(data);
}
}
answer-set-header-details.html
<dt>First:</dt>
<dd>Description</dd>
<dt>Second</dt>
<dd>Description</dd>
<p>
data will show on click of button but not <code>onInit</code>:
</p>
<p>
{{headerData}}
</p>
answer-set-header-details.component.ts
export class AnswerSetHeaderDetailsComponent implements OnInit {
constructor(private headerDataService: HeaderDataService) { }
headerData: any;
ngOnInit() {
this.headerDataService.headerData$
.subscribe(data => {
this.headerData = data[0].name;
});
}
}