角2组件 - 访问DOM(或无模板来创建组件,单纯从JS) [英] Angular 2 Component - Access DOM (or create Component without template, purely from JS)

查看:169
本文介绍了角2组件 - 访问DOM(或无模板来创建组件,单纯从JS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图与角2这里玩......了解,它仍然在阿尔法。

Trying to play with Angular 2 here... understood that it's still in alpha.

我如何访问从组件的DOM元素?具体来说,我想用到其他库如 D3 产生从code自定义DOM。我想我需要创建一个组件并以某种方式插入组件寿命周期来改变DOM与D3 ......任何想法从哪里开始挖?

How do I access DOM elements from Component? Specifically, I would like to use other libraries like d3 to generate custom DOM from code. I suppose I need to create a component and somehow plug into component life-circle to alter DOM with d3... any idea where to start digging?

我使用这个快速入门回购

谢谢!

推荐答案

如果你不介意使用指令,而不是组件很简单。对于打字稿角2.0.0 alpha.33可以使用D3采用注浆的ElementRef操作DOM:

If you don't mind using Directive instead of Component it is straightforward. For Angular 2.0.0-alpha.33 in typescript you can use D3 to manipulate the DOM by Injecting an ElementRef:

@Directive({
    selector:   'scatter-plot',
    lifecycle: [LifecycleEvent.onChange],
    properties: [ 'data' ]
})
export class ScatterPlot {

    root: Selection<any>;
    data: Array<ScatterPlotDataPoint>;

    x: (number) => number;
    y: (number) => number;

    defaultSize: string;
    circles: any;

    constructor(
        @Inject(ElementRef) elementRef: ElementRef,
        @Attribute('height') height: string,
        @Attribute('default-size') defaultSize: string
    ) {
        var el:HTMLElement = elementRef.nativeElement;
        this.root = d3.select(el);

        this.defaultSize = defaultSize ? defaultSize : "5";
        this.circles = this.root
            .append('svg')
            .attr('class', 'chart')
            .style({
                'width':  '100%',
                'height': height ? height + 'px': '',
            }).
            selectAll('circle');

    }

    render(newValue) {
        if (!newValue) return;

        this.x = d3.scale.linear().domain([-10, 110]).range([0, 250]);
        this.y = d3.scale.linear().domain([-10, 110]).range([100, 0]);

        this.circles = this.circles
            .data(newValue);

        this.circles.exit().remove();

        this.circles.enter()
            .append('circle');

        this.circles
            .transition()
            .attr("r", d => d.size ? d.size: this.defaultSize)
            .style("fill", d => d.color)
            .attr('cx', d => this.x(d.x))
            .attr('cy', d => this.y(d.y));

    }

    onChange() {
        this.render(this.data);
    }
}

这篇关于角2组件 - 访问DOM(或无模板来创建组件,单纯从JS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆