document.getElementById replacement in angular4 / typescript?
You can tag your DOM element using #someTag
, then get it with @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.
You can just inject the DOCUMENT token into the constructor and use the same functions on it
import { Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
@Component({...})
export class AppCmp {
constructor(@Inject(DOCUMENT) document: Document) {
document.getElementById('el');
}
}
Or if the element you want to get is in that component, you can use template references.