angular - 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
}
解决方案
这里有两种选择,一种是实现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
解决方案。
推荐阅读
- docker - 为什么这个正则表达式在 docker 自动构建中不匹配这个字符串
- python - 是否有可以注入方法调用的 Python 模板系统?
- entity-framework - 实体框架拦截和修改日期
- spring-boot - 该工件在本地存储库中找到,但您已明确声明应从远程存储库下载它”
- reactjs - 状态更新后无法更新组件
- mysql - MySQL - ORDER BY 子句导致 SQL_CALC_FOUND_ROWS 选择不返回数据
- sql-server - 计算同一列中日期之间的差异
- c# - SubClass中的继承等价,如何与baseClass获得相同的结果?
- c# - 为什么 transform.hasChanged 总是正确的?(即,将 hasChanged 设置为 false 是谁的工作?)
- php - PHP: E: 找不到 php-zip 包