HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptangularCritical

document.getElementById replacement in angular4 / typescript?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
typescriptangular4replacementgetelementbyiddocument

Problem

I'm working with angular4 in my practice work, and this is new for me.

In order to get HTML elements and their values, I used document.getElementById or document.getElementById.

I'm wondering if there is any replacement for this in angular.

Solution

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: `
        Some text
    `,
})
export class AppComponent implements AfterViewInit {
    @ViewChild('myDiv') myDiv: ElementRef;

    ngAfterViewInit() {
        console.log(this.myDiv.nativeElement.innerHTML);
    }
}


console.log will print Some text.

Code Snippets

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);
    }
}

Context

Stack Overflow Q#48226868, score: 236

Revisions (0)

No revisions yet.