【发布时间】:2019-08-19 00:33:12
【问题描述】:
我的 Angular 应用程序中有一个自定义结构指令,如下所示:
@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">
但我不能像使用 ngIf 时那样访问模板其余部分中声明的变量“userDocTypes”。
我想这是一种正常的行为,但我找不到这样做的好方法。
任何帮助将不胜感激。
编辑:
这就是我使用它的方式,它位于子元素中。 如前所述,如果我将其更改为 *ngIf ,它就可以正常工作:
编辑 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;
}
}
【问题讨论】:
-
您能否提供一个示例,说明您想在哪里使用
userDocTypes -
我已经编辑了问题
标签: angular angular2-directives