0

Here is my Angular function.

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
}
Malmi
  • 35
  • 1
  • 5

2 Answers2

0

There's two options here, one is to implement the OnInit interface, the other is to use template tagging and 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)
  }
}

I would recommend the AfterViewInit solution.

Stackblitz

Phix
  • 9,364
  • 4
  • 35
  • 62
  • paraEl will be available after **ngAfterViewInit**. User **render2** to interact with the dom. – Supun De Silva Sep 23 '20 at 00:51
  • Agreed if there's DOM interaction. https://stackoverflow.com/questions/39785118/difference-between-renderer-and-elementref-in-angular-2 – Phix Sep 23 '20 at 01:30
0

Following has an interaction example as well.

HTML

<p #interestedElement>
  Initial Content
</p>
<button (click)="changeContent()">Press To Change Content</button>

Component

import { Component, OnInit, ViewChild, AfterViewInit, ElementRef, Renderer2 } from 
         '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit, AfterViewInit  {
  @ViewChild('interestedElement') element: ElementRef

  constructor(private renderer: Renderer2) {
  }

  ngOnInit() {
  } 

  ngAfterViewInit() {
    console.log('ViewChild', this.element.nativeElement.innerText)
  }

  changeContent() {
    this.renderer.setProperty(this.element.nativeElement, 'innerText', 'Changed Text')

    // Yes you can do the following as well but the recommended method is above
    // this.element.nativeElement.innerText =  'Changed Text'
  }
}

Example

https://stackblitz.com/edit/angular-ivy-flthju

Some Renderer2 related documentation

https://www.digitalocean.com/community/tutorials/angular-using-renderer2

Supun De Silva
  • 1,437
  • 9
  • 15