0

I have this code:

app.component.ts

    export class AppComponent implements AfterViewInit {

      targetElement: HTMLElement;
      viewer: any;

      constructor () {}

      ngAfterViewInit() {
       this.targetElement = document.getElementById('wrapper'); // This line
      }


  app.component.html



    <div #wrapper id="wrapper" [innerHTML]=targetElement></div>

I don't want to use

document.getElementById('wrapper');

Is there an Angular way to change the line marked: // This line?

2 Answers 2

1

The Angular way is to use template reference with @ViewChild decorator

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

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

  constructor() {}

  ngAfterViewInit() {
   //use this.test
  }
}

Note this line @ViewChild('#wrapper') test: ElementRef; wrapper refers to the template reference on the html element

Another way would be to directly inject ElementRef in constructor.

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

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

  constructor(private elem: ElementRef) {}

  ngAfterViewInit() {
    this.elem.nativeElement.querySelector('#wrapper');
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Template ref can be used if you want to access the dom.

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

export class AppComponent implements AfterViewInit {

  @ViewChild('wrapper')
  wrapper: ElementRef
  viewer: any;

  constructor () {}

  ngAfterViewInit() {
  }

}


  <div #wrapper></div>

this.wrapper will have the dom node which can be used to access

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.