【发布时间】:2019-04-29 00:24:21
【问题描述】:
我正在尝试获取一个角度指令实例,即使它尚未呈现。
例如,我有一个 app-component 和 baz-directive。即使没有显示/呈现给dom,我也想获取指令实例。当然,我可以通过输入 var 来控制功能,但在我的情况下,访问实例并调用一些函数会更好/更容易。因此,它的行为应该类似于 NgIf*,不仅通过输入 var,而且通过实例函数调用。
所以我的问题是,即使它没有被渲染,我如何获得实例,或者是否有任何其他/更好的方法来处理这种情况?
import {Component, Directive, OnInit, TemplateRef, ViewChild, ViewContainerRef} from "@angular/core";
@Directive({selector: '[baz]'})
export class BazDirective
{
constructor(protected view: ViewContainerRef, protected template: TemplateRef<any>)
{
}
renderNow()
{
this.view.createEmbeddedView(this.template);
}
}
@Component({
selector: "app-root", templateUrl: "./app.component.html"
})
export class AppComponent implements OnInit
{
@ViewChild(BazDirective) bar: BazDirective
constructor()
{
}
ngOnInit(): void
{
this.bar.renderNow();
}
}
<div #bar *baz>foo</div>
【问题讨论】:
-
未显示 = 不可访问。
-
这就是问题所在,因为该指令存在,否则我猜它无法对输入 var 更改做出反应。
-
组件存在,指令不存在。它已从 dom 中删除,您无法访问它。
标签: angular angular-directive angular-components