访问 Angular2 JavaScript ES5 组件中的元素

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

我不确定 non-Typescript 语法是什么,但我相信您自己知道。

我是这样做的:

export class Navigation {

    constructor(elementRef: ElementRef) {
        // elementRef.nativeElement is the actual element
    }
}

向元素添加模板变量('#canvas')

template: '<div><canvas #canvas id="{{randomId}}"></canvas></div>'

使用@ViewChild注释

@ViewChild('canvas') canvas;

实施 AfterViewInit 并在 ngAfterViewInit() 被调用后 canvas 字段用 ElementRef 初始化。使用 canvas.nativeElement 您可以访问 <canvas> 元素。

我引用的 TS 和 ES5 之间的唯一区别是你调用的方式 ViewChild

虽然在 TS 中你可以直接使用注解 @ViewChild,在 ES5 中你必须在 Component

中使用 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);
        }
    });

这里有一个plnkr demonstrating the usage. There's another 可以帮助你多了解一点它的用法。