[英]document.getElementById replacement in angular4 / typescript?
So, im working with angular4 in my practice work and this is new for me. 所以,我在练习中使用angular4,这对我来说是新的。 Luckyly, in order to get html elements and its values i used
<HTMLInputElement> document.getElementById
or <HTMLSelectElement> document.getElementById
幸运的是,为了获取html元素及其值,我使用了
<HTMLInputElement> document.getElementById
或<HTMLSelectElement> document.getElementById
Im wondering if there is any replacement for this in angular 我想知道是否有角度更换
You can tag your DOM element using #someTag
, then get it with @ViewChild('someTag')
. 您可以使用
#someTag
标记DOM元素,然后使用@ViewChild('someTag')
获取它。
See complete example: 查看完整示例:
import {AfterViewInit, Component, ElementRef, ViewChild} from '@angular/core';
@Component({
selector: 'app',
template: `
<div #myDiv>Some text</div>
`,
})
export class AppComponent implements AfterViewInit {
@ViewChild('myDiv') myDiv: ElementRef;
ngAfterViewInit() {
console.log(this.myDiv.nativeElement.innerHTML);
}
}
console.log
will print Some text . console.log
将打印一些文本 。
You can just inject the DOCUMENT token into the constructor and use the same functions on it 您可以将DOCUMENT标记注入构造函数并在其上使用相同的函数
import { Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
@Component({...})
export class AppCmp {
constructor(@Inject(DOCUMENT) document) {
document.getElementById('el');
}
}
Or if the element you want to get is in that component, you can use template references . 或者,如果要获取的元素位于该组件中,则可以使用模板引用 。
element: HTMLElement;
constructor() {}
fakeClick(){
this.element = document.getElementById('ButtonX') as HTMLElement;
this.element.click();
}
For Angular 8 or posterior @ViewChild have an additional parameter called opts, which have two properties: read and static, read is optional. 对于Angular 8或后面的@ViewChild有一个名为opts 的附加参数 ,它有两个属性:read和static,read是可选的。 You can use it like so:
您可以像这样使用它:
@ViewChild('mydiv', { static: false }) mydiv: ElementRef;
Note this is for Angular 8 or posterior. 注意这是针对Angular 8或后部的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.