All versions of this documentation
X

Integration with Angular Download code

To use Ogma with Angular, follow those rules: initialize your Ogma instance in a service, declare this service as a provider for your application, and inject it into a component to display visualizations.

Let's write a quick Angular application that has the following components:

  • a button to add a node
  • a component that displays the instance of Ogma

OgmaService

import { Injectable } from '@angular/core';
import Ogma           from 'ogma/ogma.min';

@Injectable()
export class OgmaService extends Ogma {

  constructor () {
    super(); // not using 'new' to create an instance of Ogma, prototype chain will be broken.

    // restore the prototype chain =>  https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget
    Object.setPrototypeOf(this, new.target.prototype);
  }

  /**
   * Add a random node to the visualization and locate view.
   *
   * return {Promise<void>}
   */
  public addRandomNode(): Promise<void> {
    this.addNode({
      id: this.getNodes().size + 1,
      attributes: {
        x: Math.random() * 100,
        y: Math.random() * 100
      }
    });
    return this.view.locateGraph({
      duration: 500
    });
  }
}

Provide Ogma Service

Declare OgmaService as a provider in your App Module so it is available to all components.

//...
import { OgmaService } from './ogma.service';

@NgModule({
  declarations: [
    //...
  ],
  imports: [
    //...
  ],
  providers: [OgmaService],
  bootstrap: [
    //...
  ]
})
export class AppModule { }

Add OgmaService to a Component

Inject the OgmaService into your component. Bind Ogma to the component's container in the AfterContentInit() function to .

import { AfterContentInit, Component, ViewChild } from '@angular/core';
import { OgmaService }                            from './ogma.service';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent implements AfterContentInit {

  ViewChild('ogma_container') private container;
  title = 'Ogma + Angular';

  /**
   * param {OgmaService} ogmaService
   */
  constructor(private ogmaService: OgmaService) {}

    /**
     * Add a random node to the visualization
     */
  public addNode(): void {
    this.ogmaService.addRandomNode()
      .then(() => {
        console.log('node added.');
      });
  }

  /**
   * Ogma container must be set when content is initialized
   */
  ngAfterContentInit() {
    this.ogmaService.setContainer(this.container.nativeElement);
  }
}

The result:

Ogma+Angular