簡體   English   中英

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

我引用的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);
        }
    });

這是一個演示用法的plnkr 還有另一個答案可以幫助您更多地了解其用法。

將模板變量('#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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM