【问题标题】:Angular code does not run after "getElementByID"Angular 代码在“getElementByID”之后不运行
【发布时间】:2021-01-09 03:09:42
【问题描述】:

这是我的 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
}

【问题讨论】:

  • getHtmlContent3 未定义。 post edit你能提供你的HTML或可重现的例子
  • 控制台有错误吗?如果在 DOM 中找不到 #getContent,您应该看到 cannot read property innerText of null 或其他内容。
  • 如果你使用 Angular 为什么你使用getElementById

标签: angular


【解决方案1】:

这里有两种选择,一种是实现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 解决方案。

Stackblitz

【讨论】:

【解决方案2】:

以下还有一个交互示例。

HTML

<p #interestedElement>
  Initial Content
</p>
<button (click)="changeContent()">Press To Change Content</button>

组件

import { Component, OnInit, ViewChild, AfterViewInit, ElementRef, Renderer2 } from 
         '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit, AfterViewInit  {
  @ViewChild('interestedElement') element: ElementRef

  constructor(private renderer: Renderer2) {
  }

  ngOnInit() {
  } 

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

  changeContent() {
    this.renderer.setProperty(this.element.nativeElement, 'innerText', 'Changed Text')

    // Yes you can do the following as well but the recommended method is above
    // this.element.nativeElement.innerText =  'Changed Text'
  }
}

示例

https://stackblitz.com/edit/angular-ivy-flthju

一些 Renderer2 相关文档

https://www.digitalocean.com/community/tutorials/angular-using-renderer2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-28
    • 2014-11-06
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    相关资源
    最近更新 更多