如何访问 Angular 组件上的 TemplateRef?

Fly*_*ira 5 typescript ngx-bootstrap angular

组件 TS

ngOnInit() {
    if(somecondition)
        // This is the line of code that wont work
        this.openModal(#tempName);
}
Run Code Online (Sandbox Code Playgroud)

组件 HTML

<ng-template #tempName>
    I got some content here
</ng-template>
Run Code Online (Sandbox Code Playgroud)

this.openModal(#tempName) -> 我如何在这里访问 ngTemplate tempName?

Eli*_*seo 5

Flyn 你输入你的代码

@ViewChild('tempName') mymodal: ElementRef;
//You can NOT use this.mymodal at ngInit, the early time you can use is in ngAfterViewInit
ngAfterViewInit()
{
 if (somecondition)
   this.openModal(mymodal);
}
Run Code Online (Sandbox Code Playgroud)

  • 你可以在`ngOnInit` 中访问ViewChild 和ContentChild,只要它们是静态的,例如不是像*ngFor 这样的动态指令的一部分。说明 github.com/angular/angular/issues/19872#issuecomment-338703562。认为我们在引用 `ng-template` 时使用 `TemplateRef` 而不是 `ElementRef` (3认同)