[英]Accessing element in an Angular2 JavaScript ES5 component
Edit: As most comments so far give me the TypeScript solution, I feel I need to repeat here: Using JavaScript ES5. 编辑:到目前为止,大多数评论都给了我TypeScript解决方案,我觉得我需要在这里重复:使用JavaScript ES5。
I want to create a canvas component, where I draw data based on a bound property. 我想创建一个canvas组件,在其中基于绑定属性绘制数据。 How can I do this in Angular2 using JavaScript?
如何在Angular2中使用JavaScript做到这一点?
My approach with Angular 1 would be to get the element reference in the directive, but I can't find out how this is supposed to be done now. 我对Angular 1的处理方式是在指令中获取元素引用,但我现在不知道应该怎么做。
Here is an approach which seems to work, but I feel like washing my hands after doing this: 这是一种似乎可行的方法,但是在执行此操作后,我感觉要洗手:
(function (app) {
app.DrawingComponent = ng.core
.Component({
selector: 'my-drawing',
template: '<div><canvas id="{{randomId}}"></canvas></div>'
})
.Class({
constructor: function () {
this.randomId = "canvas" + Math.random();
},
ngAfterViewInit: function() {
var canvas = document.getElementById(this.randomId);
console.log(canvas);
}
});
})(window.app || (window.app = {}));
The only difference between the TS solution I referenced, and ES5 is the way you call ViewChild
我引用的TS 解决方案与ES5之间的唯一区别是调用
ViewChild
的方式
While with TS you can use directly the annotation @ViewChild
, in ES5 you have to use the queries
parameter in the Component 虽然与TS,你可以直接使用注释
@ViewChild
,在ES5您必须使用queries
参数的组件
app.DrawingComponent = ng.core
.Component({
selector: 'my-drawing',
template: '<div><canvas #myCanvas></canvas></div>',
// Check here! This is important!
queries : {
myCanvas : new ng.core.ViewChild('myCanvas')
}
})
.Class({
constructor: function () {},
ngAfterViewInit: function() {
console.log(this.myCanvas);
}
});
Here's a plnkr demonstrating the usage. 这是一个演示用法的plnkr 。 There's another answer that can help you to understand a little bit more its usage.
还有另一个答案可以帮助您更多地了解其用法。
Add a template variable ('#canvas') to the element 将模板变量('#canvas')添加到元素
template: '<div><canvas #canvas id="{{randomId}}"></canvas></div>'
Use @ViewChild
annotation 使用
@ViewChild
批注
@ViewChild('canvas') canvas;
Implement AfterViewInit
and and after ngAfterViewInit()
was called the canvas
field is initialized with an ElementRef
. 实现
AfterViewInit
并在ngAfterViewInit()
之后,使用ElementRef
初始化canvas
字段。 With canvas.nativeElement
you can access the <canvas>
element. 使用
canvas.nativeElement
可以访问<canvas>
元素。
I'm not sure what the non-Typescript syntax is, but I'm sure you know that youself. 我不确定非Typescript语法是什么,但是我确定您知道自己。
This is how I've done it: 这是我的方法:
export class Navigation {
constructor(elementRef: ElementRef) {
// elementRef.nativeElement is the actual element
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.