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

懵懂的女人 提交于 2019-12-24 08:04:10

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/59062387/how-do-i-create-an-htmlelement-reference-in-an-angular-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!