AngularJS2 integrates with D3.js to implement custom visualization. angularjs2d3. js

Source: Internet
Author: User
Tags export class

AngularJS2 integrates with D3.js to implement custom visualization. angularjs2d3. js

This article describes how ANGULAR2 integrates with D3.js to implement custom visualization:

Target

  1. Separation of presentation layer and logic layer
  2. Data and visualization components separated
  3. Two-way binding of data and views, real-time update
  4. Clear code structure, easy to maintain and modify

Basic Principles

Angular2 component lifecycle hook Method \ parent-child component Interaction Mechanism \ template syntax

Source code parsing

The code structure is simple. The code structure except the main page index.html and main. ts is as follows:

Code structure

App. module. ts

import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { FormsModule } from '@angular/forms';//componentsimport { AppComponent } from './app.component';import { Bubbles } from './bubbles.component';@NgModule({ declarations: [  AppComponent,  Bubbles ], imports: [  BrowserModule,  FormsModule ], providers: [], bootstrap: [AppComponent]})export class AppModule { }

App.component.html

Implement host view definition,

Two buttons. The button can be bound with a 2-Click Event, perform the corresponding action, refresh the array, and update the bubble chart;

One bubble chart sub-component. values is the INPUT attribute of the sub-component to implement communication between parent and child components. numArray is the input data array of the bubble chart, and then a randomly generated array.

<H1> <button (click) = "refreshArr ()"> start to refresh the bubble chart </button> <button (click) = "stopRefresh () "> stop refreshing the bubble chart </button> <bubbles [values] =" numArray "> </bubbles> 

App. component. ts

By specifying a 3-second refresh timer to refresh data, you must clear the array first, then add elements, and directly modify the value of the array element without changing the reference, the bubble chart cannot be refreshed.

Import {Component, OnDestroy, OnInit} from '@ angular/core'; @ Component ({selector: 'app-root', templateUrl :'. /app.component.html ', styleUrls :['. /app.component.css ']}) export class AppComponent implements OnInit, OnDestroy {intervalId = 0; numArray = []; // clear the timer private clearTimer () {console. log ('Stop refreshing'); clearInterval (this. intervalId);} // generate the random number private getRandom (begin, end) {return Math. floor (Math. random () * (end-begin);} ngOnInit () {for (let I in this. numArray) {this. numArray [I] = this. getRandom (0, 100000000); // "0", "1", "2" ,};}// the element closes the clearing timer ngOnDestroy () {this. clearTimer () ;}// start the timed refresh array refreshArr () {this. clearTimer () this. intervalId = window. setInterval () => {this. numArray = []; for (let I = 0; I <8; I ++) {this. numArray. push (this. getRandom (0, 100000000) ;}}, 3000) ;}// stop the timed refresh array stopRefresh () {this. clearTimer ();}}

Bubbles. component. ts bubble chart component class

  1. The ngOnChanges () lifecycle method is automatically called when the INPUT attribute values changes;
  2. @ ViewChild: You can obtain references to the child element svg. The # target custom variable is used to identify the svg sub-element.
Import {Component, Input, OnChanges, AfterViewInit, ViewChild} from '@ angular/core'; import {BubblesChart} from '. /bubbles. chart'; declare var d3; @ Component ({selector: 'buckets', template: '<svg # target width = "900" height = "300"> </svg>',}) export class Bubbles implements OnChanges, AfterViewInit {@ Input () values: number []; chart: BubblesChart; @ ViewChild ('target') target; // obtain the reference of the Child component constructor () {}// whenever the value of the input value values bound to the element object changes, execute the following function to dynamically change the ngOnChanges (changes) {if (this. chart) {// clear the bubble graph first, then call the render method of the bubble graph object again, and draw the Graph Based on the changed value. chart. destroy (); this. chart. render (changes. values. currentValue) ;}} ngAfterViewInit () {// initialize the bubble chart this. chart = new BubblesChart(this.tar get. nativeElement); this. chart. render (this. values );}}

Bubbles. chart. ts bubble chart class

  1. The bubble graph class defined by the d3.js syntax. It comes with a rendering method and an erasure method.
  2. Introduce <script src = "// d3js.org/d3.v2.js"> </script>
Declare var d3; // define a bubble chart class // Exports the visualization moduleexport class BubblesChart {target: HTMLElement; // constructor, draw constructor (target: HTMLElement) {this.tar get = target;} based on an HTML Element Object ;} // render the input parameter as a numerical value to complete the rendering of an array-based Bubble chart render (values: number []) {console. log ('start rendin'); console. log (values); d3.select(this.tar get) // Get the old circles. selectAll ('circle '). data (values ). enter () // For each new data point, append a circle to the target SVG. append ('circle') // Apply several style attributes to the circle. attr ('R', d => Math. log (d) // radius. attr ('fill', '# 5fc') // color. attr ('stroke', '#333') // contour color. attr ('transform', (d, I) => {// move the position var offset = I * 30 + 3 * Math. log (d); return 'translate ($ {offset}, $ {offset}) ';});} destroy () {d3.select(this.tar get ). selectAll ('circle '). remove ();}}

Effect display

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.