如何在Angular组件中创建HtmlElement引用? [英] How do I create an HtmlElement Reference in an Angular component?

查看:657
本文介绍了如何在Angular组件中创建HtmlElement引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件MyNodeComponent,它在我的Angular 7.2.15中将target HTML元素作为 input 对象的一部分:

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}];
  ...
}

问题是我不确定如何以动态方式将HTML DOM节点发送到目标.尤其是在页面上可能存在具有不同层次关系的MyNode的多个实例:

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>

我如何定义inputObjectDefinition以包含来自打字稿组件内部的对target1和target2的引用?我是否使用document.getElementById(它始终返回null,但我可能使用的是错误的)?其他方式?

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?

回答强制性的您为什么要这样做?"实际上,我的问题是MyNodeComponent被用来将dom节点发送到html2Canvas库,以便我可以将页面的一部分或一部分呈现为图像.

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.

推荐答案

看看Angular的ElementRef( https://angular.io/api/core/ElementRef ).这使您可以访问DOM中的Element.

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

您可以在这里看到实际效果; https://stackblitz.com/edit/angular-elementref-example

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);
}

如果要动态选择它们,可以通过使用ViewChildren引用某个指令来实现.

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

这篇关于如何在Angular组件中创建HtmlElement引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆