javascript - 使用 ng-template 清空原生元素
我使用 Angular 5。
在我的 component 中我有:
@ContentChild('contentTemplate') contentTemplate: TemplateRef<any>;
我的 HTML:
<data-grid-column>
<ng-template #contentTemplate>
<span class="elo">Hello</span>
</ng-template>
</data-grid-column>
我正在嘗試查看:
ngAfterViewChecked () {
console.log(this.contentTemplate.elementRef.nativeElement);
}
但是輸出是:
<!---->
怎麼了?
答案#1
我希望它會奏效。
<ng-container #contentTemplate><span class="elo">Hello</span></ng-container>
答案#2
ng-template - 是一個用於渲染 HTML 的 Angular 元素。它從不會被直接顯示。事實上,在渲染視圖之前,Angular 會將
及其內容替換為一個註解
根據官方文件。
參考
- https://angular.io/guide/structural-directives#the-ng-template
我不知道你為什麼在這裡使用 ng-template,但你可以改用 ng-container,這樣會顯示你的內容。
另外,由於你在 HTML 元素上使用了 # 本地變數,你需要改用 ViewChild,像這樣 -
@ViewChild('contentTemplate') contentTemplate: any;
