[英]Accessing element in an Angular2 JavaScript ES5 component
編輯:到目前為止,大多數評論都給了我TypeScript解決方案,我覺得我需要在這里重復:使用JavaScript ES5。
我想創建一個canvas組件,在其中基於綁定屬性繪制數據。 如何在Angular2中使用JavaScript做到這一點?
我對Angular 1的處理方式是在指令中獲取元素引用,但我現在不知道應該怎么做。
這是一種似乎可行的方法,但是在執行此操作后,我感覺要洗手:
(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 = {}));
我引用的TS 解決方案與ES5之間的唯一區別是調用ViewChild
的方式
雖然與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);
}
});
將模板變量('#canvas')添加到元素
template: '<div><canvas #canvas id="{{randomId}}"></canvas></div>'
使用@ViewChild
批注
@ViewChild('canvas') canvas;
實現AfterViewInit
並在ngAfterViewInit()
之后,使用ElementRef
初始化canvas
字段。 使用canvas.nativeElement
可以訪問<canvas>
元素。
我不確定非Typescript語法是什么,但是我確定您知道自己。
這是我的方法:
export class Navigation {
constructor(elementRef: ElementRef) {
// elementRef.nativeElement is the actual element
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.