Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.getElementById replacement in angular4 / typescript?

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 <HTMLInputElement> document.getElementById or <HTMLSelectElement> document.getElementById.

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

like image 926
Nino Gutierrez Avatar asked Jan 12 '18 13:01

Nino Gutierrez


People also ask

How do I replace documents getElementById in TypeScript?

Use ElementRef as getElementById Replacement in Angular Using TypeScript. The ElementRef of AngularJs is a wrapper around an HTML element, containing the property nativeElement and holding the reference to the underlying DOM object. Using ElementRef , we can manipulate the DOM in AngularJs using TypeScript.

Can we use document getElementById in TypeScript?

To use the document. getElementById() method in TypeScript: Use a type assertion to type the selected element correctly. Use a type guard to make sure the variable does not store a null value.

What can I use instead of getElementById?

Yes, you can use the document. querySelectorAll function to query any CSS selector, or you can use document. getElementsByClassName to query based on class.

Can we use document getElementById in angular?

The getElementById method returns the element with the ID Attribute with the specified value. This method is most common in HTML DOM and is used almost every time we manipulate, get info from, or element in our document.


2 Answers

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.

like image 153
Alexandre Annic Avatar answered Oct 01 '22 13:10

Alexandre Annic


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.

like image 35
Suren Srapyan Avatar answered Oct 01 '22 12:10

Suren Srapyan