英文:
How to access element of <ng-template>
问题
我正在尝试通过ID访问位于<ng-template>内部的元素,并在加载器为false时显示<ng-template>。因此,在订阅函数中,在加载器变为false后,我的<ng-template>被渲染,在订阅方法本身中,我试图访问我的'gif-html',但我得到了null。
英文:
I am trying to access element by id which is inside the <ng-template>
and I am showing that <ng-template>
when loader is false
. So in subscribe
function after loader becomes false
my <ng-template> is renedering, and in subscribe method itself I am trying to access my 'gif-html' but I am getting it null
<div class="my-loader" *ngIf="loader; else show_form_content">
<ngx-loading [show]="loader"></ngx-loading>
</div>
<ng-template #show_form_content>
<div class="gifTimer" id="gif-html">
</div>
</ng-template>
</div>
getMyData() {
this.loader = true;
this.myService
.getData()
.subscribe((response) => {
this.loader = false;
if (response.status === 'success') {
let gifHtml = document.getElementById('gif-html');
console.log('gifHtml', gifHtml)
}
});
}
ngOnInit(){
this.getMyData()
}
答案1
得分: 1
getElementById方法返回null是因为当你尝试访问时,ng-template的内容尚未在DOM中呈现。
ng-template是一个结构性指令,它不会立即呈现其内容。相反,它作为一个模板,可以通过ngIf或ngTemplateOutlet指令进行条件性渲染。
HTML
<div class="my-loader" *ngIf="loader; else show_form_content">
<ngx-loading [show]="loader"></ngx-loading>
</div>
<ng-template #show_form_content>
<div class="gifTimer" id="gif-html">
</div>
</ng-template>
我将id="gif-html"添加到了div元素中作为模板引用变量。
import { ViewChild, ElementRef, AfterViewInit } from '@angular/core';
export class YourComponent {
@ViewChild('gif-html', { static: false }) gifHtmlRef!: ElementRef;
ngAfterViewInit() {
this.getMyData();
}
getMyData() {
this.loader = true;
this.myService
.getData()
.subscribe((response) => {
this.loader = false;
if (response.status === 'success') {
console.log('gifHtml', this.gifHtmlRef.nativeElement);
}
});
}
}
我希望这对你有所帮助。
英文:
getElementById method is returning null because the ng-template content is not rendered in the DOM when you're trying to access it.
The ng-template is a structural directive that doesn't render its content immediately. Instead, it serves as a template that can be rendered conditionally using the *ngIf or *ngTemplateOutlet directives.
HTML
<div class="my-loader" *ngIf="loader; else show_form_content">
<ngx-loading [show]="loader"></ngx-loading>
</div>
<ng-template #show_form_content>
<div class="gifTimer" id="gif-html">
</div>
</ng-template>
I added the id="gif-html" template reference variable to the div element.
import { ViewChild, ElementRef, AfterViewInit } from '@angular/core';
export class YourComponent {
@ViewChild('gif-html', { static: false }) gifHtmlRef!: ElementRef;
ngAfterViewInit() {
this.getMyData();
}
getMyData() {
this.loader = true;
this.myService
.getData()
.subscribe((response) => {
this.loader = false;
if (response.status === 'success') {
console.log('gifHtml', this.gifHtmlRef.nativeElement);
}
});
}
}
i hope it's help
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论