[英]How do I create an HtmlElement Reference in an Angular component?
I have a component MyNodeComponent
that takes a target
HTML element as part of the input object in my Angular 7.2.15
:我有一个组件
MyNodeComponent
,它将target
HTML 元素作为我的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.问题是我不确定如何以动态方式将 HTML DOM 节点发送到目标。 Especially as there could be multiple instances of MyNode on a page with different hierarchical relationships:
尤其是在具有不同层次关系的页面上可能有多个 MyNode 实例:
<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?我将如何定义
inputObjectDefinition
以包含从打字稿组件内部对 target1 和 target2 的引用? Do I use document.getElementById (it keeps returning null but I may be using it wrong)?我是否使用 document.getElementById(它一直返回 null,但我可能使用错误)? 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.
问题实际上 MyNodeComponent 用于将 dom 节点发送到 html2Canvas 库,以便我可以将页面的一部分或部分呈现为图像。
Take a look at Angular's ElementRef ( https://angular.io/api/core/ElementRef ).看看 Angular 的 ElementRef ( https://angular.io/api/core/ElementRef )。 This gives you access to the Element in the DOM.
这使您可以访问 DOM 中的 Element。
You can see this in action here;你可以在这里看到它的实际效果; https://stackblitz.com/edit/angular-elementref-example
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.如果你想动态地选择这些,你可以通过引用使用 ViewChildren 的指令来实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.