"Exploring the world of Typescript with the Drawflow library

Currently, I am integrating the fantastic Drawflow library created by @Jerosoler (available at: https://github.com/jerosoler/Drawflow) into my PrimeNg project.

User @BobBDE has provided typescript definitions for this library here: https://www.npmjs.com/package/@types/drawflow

My project utilizes PrimeNg with Angular 11 and Typescript 4.

I have successfully installed both the library and the definitions using npm commands. Everything seems to be in order as I can locate the JS library, and the definitions to use within Typescript.

Nevertheless, I am encountering an undefined error and I am having difficulty identifying what could possibly be incorrect...

In my component's HTML, I have included the following:

<div #drawflowDiv></div>

To access the div in my component's Typescript:

@ViewChild('drawflowDiv', {static: true}) 
drawflowDiv: HTMLElement;

Subsequently, in my ngOnInit function, I have the following setup:

ngOnInit(): void {
    console.log(this.drawflowDiv);
    const editor = new drawflow(this.drawflowDiv);
    editor.reroute = true;
    editor.editor_mode = 'edit';
    editor.drawflow = {.....}; // Default example JSON for the library
    editor.start();
}

There are no errors evident in the code, and the drawflow library is correctly connected. The console.log provides all the details of the HTML element within the div, indicating that it is not undefined. A screenshot of the console log is attached to this post.

Your assistance would be greatly appreciated, and I hope that someone here might have a solution.

Thanks in advance!

View screenshot of console output here

Answer №1

For a more reusable approach, consider encapsulating the code within a directive:

Directive file: app-draw-flow.directive.ts

import { Directive, ElementRef, OnInit } from '@angular/core';
import Drawflow from 'drawflow';

@Directive({
  selector: '[appDrawFlow]'
})
export class DrawFlowDirective implements OnInit {

  editor: Drawflow;

  constructor(private hostElementRef: ElementRef) { }

  ngOnInit() {
    if (!!this.hostElementRef?.nativeElement) {
      const { nativeElement } = this.hostElementRef;
      this.initializeDrawFlow(nativeElement);
    }
  }

  private initializeDrawFlow(element: HTMLElement): void {
    try {
      if (!!element) {
        this.editor = new Drawflow(element);
        this.editor.reroute = true;
        this.editor.editor_mode = 'edit';
        // this.editor.drawflow = {}
        this.editor.start();
      } else {
        console.error('Drawflow host element does not exist');
      }

    } catch (error) {
      console.error('Unable to start Drawflow', error);
    }
  }
}

Don't forget to include DrawFlowDirective as a declaration in the parent feature module where you plan to use it.

Here's an example of how to use it in your template:

<div appDrawFlow></div>

If you encounter any issues running it, verify your module declarations. Here is an example (partial snippet of app module):

@NgModule(
  {declarations: [DrawFlowDirective]}
)
export class AppModule { }

Answer №2

To include a drawing flow in your HTML component, simply add the following code:

<div id="drawflowContainer"></div>

Then, in the ngOnInit function:

this.drawFlowChart = new Drawflow(document.getElementById('drawflowContainer'));
this.drawFlowChart.initialize();
...

Answer №3

To properly initialize your editor, make sure to include the nativeElement in its creation:

Ensure that when you instantiate the drawflow editor, you pass in this.drawflowDiv.nativeElement like this:
const editor = new drawflow(this.drawflowDiv.nativeElement);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What potential outcomes arise from independently initiating multiple components simultaneously?

Here is a scenario where I am able to achieve the following: @NgModule({ imports: [BrowserModule], declarations: [AppComponent, BComponent], bootstrap: [AppComponent, BComponent] <---------- here two components }) By doing this, it will ge ...

Could it be possible for a Firestore onUpdate trigger's change parameter, specifically change.after.data() and change.before.data(), to become null or undefined?

Presented below is a snippet of my cloud function exports.onUpdateEvent = functions.firestore.document('collection/{documentId}') .onUpdate((change, context) => { const after: FirebaseFirestore.DocumentData = change.after.data(); const ...

Executing npm prepublish on a complete project

I am facing a situation with some unconventional "local" npm modules that are written in TypeScript and have interdependencies like this: A -> B, C B -> C C -> D When I run npm install, it is crucial for all TypeScript compilation to happen in t ...

React Hot Toast useState is unfortunately not exported from the React library

While working on a Next.js project, I encountered an issue when trying to use react-hot-toast. When I attempted to import it into any file, I received the following error message: Error - ./node_modules/react-hot-toast/dist/index.mjs Attempted import erro ...

Creating a seamless integration between Angular 2's auth guard and observables to enhance application security

I'm having trouble setting up an auth guard for one of my routes because I am unsure how to implement it with an observable. I am using ngrx/store to store my token. In the guard, I retrieve it using this.store.select('auth'), which returns ...

Angular displays the error message TS2339, stating that the property 'handleError' is not found on the 'HeroService' type

Hey everyone, I know there are already a few questions out there about Typescript compilation errors, but I'm facing a unique challenge that I can't quite figure out. I'm currently working on the Angular Tour of Heroes app and trying to com ...

Conflict arises due to an override of react-error-overlay@^6.0.9 conflicting with a direct dependency

After updating my node version, I encountered an error every time I attempted to install a new package or run npm install. Here is the specific error message that kept showing up: npm ERR! code EOVERRIDE npm ERR! Override for react-error-overlay@^6.0.9 co ...

"Converting to Typescript resulted in the absence of a default export in the module

I converted the JavaScript code to TypeScript and encountered an issue: The module has no default export I tried importing using curly braces and exporting with module.exports, but neither solution worked. contactController.ts const contacts: String[ ...

Passing properties from the parent component to the child component in Vue3JS using TypeScript

Today marks my inaugural experience with VueJS, as we delve into a class project utilizing TypeScript. The task at hand is to transfer the attributes of the tabsData variable from the parent component (the view) to the child (the view component). Allow me ...

I am having trouble resolving 'otp-input-react' in my project directory at D:projectappsrc

I have been troubleshooting this issue but haven't been able to find a solution yet. I even tried uninstalling and reinstalling the package, but it still isn't working as expected. Here are some images for better clarity: https://i.stack.imgur.c ...

Switching from JavaScript to TypeScript resulted in React context not being located in its respective file

I previously had my context and context provider set up in a file, and everything was working perfectly. However, I recently decided to convert all of my files to TypeScript, including this one. Unfortunately, I've encountered a strange issue that I c ...

Refining Generic Types in TypeScript

Why does the generic type not narrow after the type guard in typescript v4.4.4? Is there a way to resolve this issue? type Data = X | Y | Z type G<T extends Data> = { type: 'x' | 'y' data: T } type X = { name: string } type ...

When attempting to run npm install for @types/jquery, an error is returned stating "Invalid name: @types/jquery"

npm install @types/jquery npm ERR! Windows_NT 10.0.10586 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-c ...

Ensuring TypeScript's strict null check on a field within an object that is part of an

When using TypeScript and checking for null on a nullable field inside an object array (where strictNullCheck is set to true), the compiler may still raise an error saying that 'Object is possibly undefined'. Here's an example: interface IA ...

React JS integrated with Stripe

I am in need of generating a token with Stripe.js within a React JS environment, however, I have been unable to find a straightforward solution. In a node.js setting, the process would typically look something like this: stripeClient.tokens.create({ ...

Error message in Docker: "Command /bin/sh: 1: ng: not found; please make sure Angular

While attempting to create a docker image for my Angular app, I encountered an issue where it crashes on RUN ng build --prod and the error message displayed is: /bin/sh: 1: ng: not found The command '/bin/sh -c ng build --prod' returned a non-ze ...

the Sprite fails to appear on the screen

Can you help me figure out how to fix the issue I'm having with loading images in this component? Currently, when I refresh the page, the image does not load properly and appears resized to 1 pixel width. Should I wait for the image to fully load befo ...

CreateAsyncModule using an import statement from a variable

When trying to load a component using defineAsyncComponent, the component name that should be rendered is retrieved from the backend. I have created a function specifically for loading the component. const defineAsyncComponentByName = (componentName: strin ...

The KeyValuePair<string, Date> type in Typescript cannot be assigned to the KeyValuePair<number, string> type

I encountered the following issue: An error occurred stating that Type 'KeyValuePair<string, Date>' is not assignable to type 'KeyValuePair<number, string>'. Also, it mentioned that Type 'string' is not assignab ...

What methods does the TypeScript compiler use to locate npm packages containing types?

When configuring the typescript compiler, you can utilize the tsconfig.json file. This will also give you access to options for finding type definition files using the typeRoots key. By default: All visible "@types" packages are automatically included in ...