首页 > 解决方案 > Angular 代码在“getElementByID”之后不运行

问题描述

这是我的 Angular 函数。

getUserdata(){
    console.log("Test")//This is Working
    const getHtmlContent = document.getElementById('getContent') as HTMLElement;
    const getTextContent = getHtmlContent.innerText;
    console.log("Test");//This is not working
    console.log(getTextContent);//This is not working
}

标签: angular

解决方案


这里有两种选择,一种是实现OnInit接口,另一种是使用模板标记和AfterViewInit

<p id="para" #para></p>
import { Component, OnInit, ViewChild, AfterViewInit, ElementRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit, AfterViewInit  {
  name = 'Angular';
  @ViewChild('para') paraEl: ElementRef

  ngOnInit() {
    const p = document.getElementById('para')
    console.log('ngInit', p.innerText)
  } 

  ngAfterViewInit() {
    console.log('ViewChild', this.paraEl.nativeElement.innerText)
  }
}

我会推荐AfterViewInit解决方案。

堆栈闪电战


推荐阅读