我已经实现了一个指令,决定它是否会呈现一个元素。
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
export class MyDirective {
constructor(private _templateRef: TemplateRef<any>,
private _viewContainer: ViewContainerRef) {
}
@Input() set method() {
this._viewContainer.clear();
if (// some logic here //) {
this._viewContainer.createEmbeddedView(this._templateRef) // render element
}
}
我现在的问题是我想渲染元素,但我还需要决定是否启用它。有没有办法在指令本身内执行此操作?
答案 0 :(得分:1)
可以像在内置ngIf
directive中一样完成它:
if (// some logic here //) {
this._viewContainer.createEmbeddedView(this._templateRef) // render element
} else {
this._viewContainer.clear();
}
答案 1 :(得分:0)
如果您不想清除(this._viewContainer.clear()),则不可能,可能应该尝试显示一个虚拟组件。
git