Search code examples
angularngx-chartsngx-graph

How to call Center and Fit In View pragmatically on ngx-graph


In this ngx-graph live demo, under the Options section, there are buttons to Center, Fit In View, etc. I would like to implement these in my solution. However, I cannot find any documentation on how to make these calls, and the demo doesn't provide its source.

In this reference doc it lists center$ and zoomToFit$ observables, but so far I have been unable to successfully subscribe to or trigger these. When I inspect using chrome dev tools it seems that these elements do not exist on the inspected object.

Given the following (simplified) graph setup, how can I wire up the (click) handler of the button at the top to trigger the Centre function?

<button (click)="myGraph.xxxxxx?">Center</button>

<ngx-graph
  #myGraph
  [links]="links"
  [nodes]="nodes"
  [curve]="curve">

  <ng-template #defsTemplate>
    <svg:marker id="arrow" viewBox="0 -5 10 10" refX="8" refY="0" markerWidth="4" markerHeight="4" orient="auto">
      <svg:path d="M0,-5L10,0L0,5" class="arrow-head" />
    </svg:marker>
  </ng-template>

  <ng-template #nodeTemplate let-node>
    <svg:g>
      <svg:rect [attr.width]="node.width" [attr.height]="node.height" [attr.fill]="node.options.color" />
      <svg:text alignment-baseline="central" [attr.x]="10" [attr.y]="node.height / 2">{{node.label}}</svg:text>
    </svg:g>
  </ng-template>

  <ng-template #linkTemplate let-link>
    <svg:g class="edge">
      <svg:path>
      </svg:path>
        <svg:text class="edge-label" text-anchor="middle" style="fill: #000000;font-size: 13px">
          <textPath class="text-path" [attr.href]="'#' + link.id" [style.dominant-baseline]="link.dominantBaseline" startOffset="50%">
            {{link.label}}
        </textPath>
      </svg:text>
    </svg:g>
  </ng-template>

</ngx-graph>

Solution

  • I believe these are only exposed in version 6 of the component (NPM Link), so upgrade to that first. Then you can do:

    <button (click)="myGraph.zoomToFit() && myGraph.center()">Center</button>
    

    Not sure if the observables work (haven't tested myself), but you'd use them something like:

    <ngx-graph [center$]="center$"></ngx-graph>
    
    class MyComponent {
      center$ = new Subject<any>();
      doCenter() {
        // trigger center
        this.center$.next();
      }
    }