In angular 5 there is built in feature for ngIf
directive - as syntax
. You can find the example here https://toddmotto.com/angular-ngif-async-pipe.
In the example below user$
is an observable.
<div *ngIf="(user$ | async) as user; else loading">
<user-profile
[user]="user.profile">
</user-profile>
<user-messages
[user]="user.messages">
</user-messages>
</div>
<ng-template #loading>
Loading stuff...
</ng-template>
I've created my own directive that replaces content of element with loading spinner and I want to enable passing observable as input, see code below.
@Directive({ selector: '[appLoadingData]' })
export class LoadingDataDirective {
constructor(
private templateRef: TemplateRef<any>,
private viewContainerRef: ViewContainerRef,
private componentFactoryResolver: ComponentFactoryResolver
) { }
@Input()
set appLoadingData(data: any) {
if (data != null) {
if (data.subscribe) {
this.addLoadingPlaceholder();
data.subscribe(() => {
setTimeout(() => this.addView(), 0);
});
} else {
this.addView();
}
} else {
this.addLoadingPlaceholder();
}
}
private addView() {
this.viewContainerRef.clear();
this.viewContainerRef.createEmbeddedView(this.templateRef);
}
private addLoadingPlaceholder() {
this.viewContainerRef.clear();
const loadingComponentFactory = this.componentFactoryResolver.resolveComponentFactory(LoadingDataComponent);
this.viewContainerRef.createComponent(loadingComponentFactory);
}
}
And I want to use in the next way
<ng-container *ngFor="let chartConfig of chartsConfigs">
<div class="chart-wrapper"
*appLoadingData="(chartConfig.chartGroups$ | async) as groups">
<chart-summary [chartData]="groups"
[chartOptionsName]="chartConfig.chartType">
</chart-summary>
</div>
</ng-container>
or ideally *appLoadingData="chartConfig.chartGroups$ as groups"
Without as syntax(*appLoadingData="chartConfig.chartGroups$ | async"
and [chartData]="chartConfig.chartGroups$ | async"
), after my loader dismissed there is a delay, I think it happens because on the addView()
in directive, async pipe called second time. I want to implement as syntax
like for ngIf directive. I've tried to use it like this: *appLoadingData="(chartConfig.chartGroups$ | async) as groups"
, but unfortunately in this case groups
is always undefined
.
How to implement as syntax
in custom directive?