У меня есть специальная структурная директива в моем угловом приложении, например:
@Directive({
selector: '[appIfData]'
})
export class IfDataDirective {
private hasView = false;
@Input()
set appIfData(condition: boolean) {
if (condition && !this.hasView) {
this.viewContainerRef.clear();
this.viewContainerRef.createEmbeddedView(this.templateRef);
this.hasView = true;
} else if (!condition) {
this.viewContainerRef.clear();
const factory = this.componentFactoryResolver.resolveComponentFactory(ContentMessageComponent);
const messageComponentRef = this.viewContainerRef.createComponent(factory);
messageComponentRef.instance.message = 'No data is available yet';
messageComponentRef.instance.icon = 'fas fa-info';
this.hasView = false;
}
}
}
Использование его в HTML-шаблоне:
<ng-container *appIfData="(referenceService.documentUserTypes$ | async) as userDocTypes">
Но я не могу получить доступ к объявленной переменной userDocTypes в остальной части шаблона, как я делал, например, при использовании ngIf
.
Я думаю, это нормальное поведение, но я не могу найти хороший способ сделать это.
Любая помощь будет принята с благодарностью.
РЕДАКТИРОВАТЬ:
Вот как я это использую, это в дочернем элементе.
Как уже было сказано, он работает нормально, если я просто изменил его на * ngIf:
![enter image description here](https://i.stack.imgur.com/OTMAe.png)
РЕДАКТИРОВАТЬ 2:
Обновленная директива
@Directive({
selector: '[appIfData]'
})
export class IfDataDirective {
private hasView = false;
@Input()
set appIfData(data: any) {
if (data && !this.hasView) {
this.viewContainerRef.clear();
this.viewContainerRef.createEmbeddedView(this.templateRef, { appIfData: data });
this.hasView = true;
} else if (!data) {
this.viewContainerRef.clear();
const factory = this.componentFactoryResolver.resolveComponentFactory(ContentMessageComponent);
const messageComponentRef = this.viewContainerRef.createComponent(factory);
messageComponentRef.instance.message = 'No data is available yet';
messageComponentRef.instance.icon = 'fas fa-info';
this.hasView = false;
}
}