How do I create an HtmlElement Reference in an Angular component?

11,969

Take a look at Angular's ElementRef (https://angular.io/api/core/ElementRef). This gives you access to the Element in the DOM.

You can see this in action here; https://stackblitz.com/edit/angular-elementref-example

In your case, you would;

@ViewChild("target1", {read: ElementRef, static: true}) target1ref: ElementRef; // gets #target1
@ViewChild("target2", {read: ElementRef, static: true}) target2ref: ElementRef; // gets #target2

ngAfterViewInit(): void {
    console.log(this.target1ref.nativeElement);
    console.log(this.target2ref.nativeElement);
}

If you want to select these dynamically, you can do so by referencing say a Directive using ViewChildren instead.

Share:
11,969
IcedDante
Author by

IcedDante

Updated on June 04, 2022

Comments

  • IcedDante
    IcedDante almost 2 years

    I have a component MyNodeComponent that takes a target HTML element as part of the input object in my Angular 7.2.15:

    @Component({
      selector: 'my-node',
      templateUrl: './my-node.component.html'
    })
    
    export class MyNodeComponent implements OnInit, OnChanges, AfterViewInit {
      @Input() inputObject: [{target: HTMLElement, desc: string}];
      ...
    }
    

    The problem is I am not sure how to send an HTML DOM node to target in a dynamic fashion. Especially as there could be multiple instances of MyNode on a page with different hierarchical relationships:

    <body>
      <my-node [inputObject]="inputObjectDefinition"></my-node> <!-- target should refer to target1 -->
    
      <p id="target1" #target1>Hello</p>
    
      <div id="target2" #target2>
      </div> 
    </body>
    

    How would I define inputObjectDefinition to contain references to target1 and target2 from inside a typescript conmponent? Do I use document.getElementById (it keeps returning null but I may be using it wrong)? Some other way?

    To answer the mandatory "why are you doing this?" question in reality the MyNodeComponent is being used to send a dom node to the html2Canvas library so that I can render part or parts of the page to an image.

  • IcedDante
    IcedDante over 4 years
    static is not a property of ViewChild args.
  • Ralpharoo
    Ralpharoo over 4 years
    @IcedDante It sure is, official documentation here; angular.io/api/core/ViewChild if you are not using the latest stack, can you please include the specific angular versions in your post? Cheers
  • IcedDante
    IcedDante over 4 years
    sorry about that. I'm 7.x and I will add that info to the post