Angular 2 Component - Access DOM (or create Component without template, purely from JS)

后端 未结 5 1352
滥情空心
滥情空心 2021-02-05 06:41

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

How do I access DOM elements from Component? Specifically, I would like to use other librarie

5条回答
  •  南旧
    南旧 (楼主)
    2021-02-05 07:05

    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;
        data: Array;
    
        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);
        }
    }
    

提交回复
热议问题