你可以看到他们正在使用
_context
变量。
https://github.com/angular/angular/blob/master/packages/common/src/directives/ng_if.ts
另见@yurzui答案。
How to declare a variable in a template in Angular2
我的最终结果:
export class LoadingDataDirective {
context: any = {};
constructor(
private templateRef: TemplateRef<any>,
private viewContainerRef: ViewContainerRef,
private componentFactoryResolver: ComponentFactoryResolver
) { }
@Input()
set appLoadingData(data: any) {
if (data != null) {
if (this.isObservable(data)) {
this.addLoadingPlaceholder();
const subscription = data.subscribe((observableResult: any) => {
this.addView(observableResult);
subscription.unsubscribe();
});
} else {
this.addView(data);
}
} else {
this.addLoadingPlaceholder();
}
}
private addView(contextData: any) {
this.context.$implicit = this.context.appLoadingData = contextData;
this.viewContainerRef.clear();
this.viewContainerRef.createEmbeddedView(this.templateRef, this.context);
}
private addLoadingPlaceholder() {
this.viewContainerRef.clear();
const loadingComponentFactory = this.componentFactoryResolver.resolveComponentFactory(LoadingDataComponent);
this.viewContainerRef.createComponent(loadingComponentFactory);
}
private isObservable(data: any): boolean {
return !!data.subscribe;
}
}
chartConfig.charGroup$
-是可观察的吗
<ng-container *ngFor="let chartConfig of chartsConfigs">
<div class="chart-wrapper"
*appLoadingData="chartConfig.chartGroups$ as groups">
<chart-summary [chartData]="groups"
[chartOptionsName]="chartConfig.chartType">
</chart-summary>
</div>
</ng-container>