"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

Encountering a timeout issue while attempting to utilize npx create-react-app

Every time I attempt to execute this code, an error pops up: npm ERR! Response timeout while trying to fetch https://registry.npmjs.org/@typescript-eslint%2fparser (over 30000ms) The log shows the following: 205 warn notsup SKIPPING OPTIONAL DEPENDENCY: ...

How can TypeScript be forced to output a specific data type?

I've created a generic "fetcher" function that is designed to handle different types of entities. However, I'm encountering an issue where TypeScript is inferring the return type based on all possible conditions within the function. Is there a w ...

Stop the direct importing of modules in Angular applications

I have a feature module that declares components and also configures routing through a static function. @NgModule({ declarations: FEATURE_COMPONENTS, entryComponents: FEATURE_COMPONENTS, imports: [ UIRouterModule, ... ] }) export class Fea ...

The elusive nodemailer greeting remains unacknowledged on its own SMTP server

I am currently working on setting up an email system using nodemailer with a company-owned SMTP server. Here is my code snippet: Const transporter = nodemailer.createTransport({ host : smtp.example.com, Port:25, Tls: { rejectUnauthorized: false} }); ...

I'm facing an issue with running npm start on my react project ever since I installed babel-cli

YTGJAI@DESKTOP-DOAIF41 MINGW64 ~/Desktop/LYNDA MERN/Exercise Files/Ch02/02_01/start/dist $ npm start [email protected] start c:\Users\mctumbaga\Desktop\LYNDA MERN\Exercise Files\Ch02\02_01\start httpster -d ...

Webpack 5 along with Babel build is experiencing an issue where functions are not

I have been working on creating a React component and then publishing it to npm. I am using webpack 5 along with babel for the build process. Everything seems to be successful in building the component, but when I try to use it, I encounter an error in the ...

Manipulating datetime format within an input element of type date using Angular's ngModel

I have a date input in my form that is populated from the controller with a string value for 'dateOfDiagnosis'. The format of this string includes the time as well, like this: "2010-09-08T00:00:00" To bind this value to an input field in Angu ...

Vee-Validate: Are flags on the field value yielding undefined results? Explained with TypeScript

The documentation states that by using a flag on the value of a field, I should be able to obtain a boolean. For example: computed: { isFormDirty() { return Object.keys(this.fields).some(key => this.fields[key].dirty); } }, I am working ...

There was an issue when trying to create symlinks for the sprkl binaries in /usr/local/bin

I encountered an error while attempting to install this extension on WSL. Any suggestions on how to resolve this issue? I have already tried editing and adding PATH Variables. :~$ npx @sprkl/scripts install ...

The error message "printer.node is not a valid Win32 application" indicates that the

I created a node API for my Angular application that utilizes the node-printer package to print PDF files generated by node. However, when I attempted to run my application using nodemon, an error occurred. Error message: "node printer.node is not a val ...

Is it possible to incorporate an NPM Package into an Ionic Project?

It really is that easy... I'm trying to figure out how to configure and use a Node Module in Ionic. It's not an Ionic plugin, but rather a node package. Each package on NPM comes with instructions on how to set it up using JavaScript. However, I ...

The ESLINT_NO_DEV_ERRORS flag appears to be ineffective in my Typescript project

Currently, my project involves using the following tools: Yarn Typescript Create React App ESLint Make (Makefile) Fish shell During development, I encounter ESLint errors that prevent my project from compiling. To run my project, I use make run, which es ...

Modify the JSON format for the API POST request

I need assistance with making an API POST call in Angular 8. The JSON object structure that needs to be sent should follow this format: -{}JSON -{}data -[]exp +{} 0 +{} 1 However, the data I am sending is currently in this format: - ...

Firestore query failing to retrieve most recent data

I have implemented a route guard in Angular that validates a specific value in firestore before granting access to the designated route. The component is accessed only after an HTTP cloud function has finished executing. This cloud function generates an o ...

Can SKIP_FLIGHT_CHECK=true and openssl-legacy-provider be safely utilized in a React script when running npm start?

I've been working on a React app that contains outdated versions of the libraries listed in the package.json file. For example: "react": "^16.3.1", "react-scripts": "^3.0.1" ... While trying to install package ...

When running a Docker container, the npm module may not be found

I'm encountering an issue while trying to run my Vue application with Docker. Upon updating npm packages locally, I encounter the following error: - Building for production... ERROR Failed to compile with 1 error8:17:57 AM This relative module was n ...

What is the reason behind a tuple union requiring the argument `never` in the `.includes()` method?

type Word = "foo" | "bar" | "baz"; const structure = { foo: ["foo"] as const, bar: ["bar"] as const, baX: ["bar", "baz"] as const, }; const testFunction = (key: keyof typeof sche ...

What causes the namespace to shift when utilizing npm for installing a library?

I've been attempting to integrate whammy.js into a project. The initial line in the source code is window.Whammy = (function(){ yet, after running npm i and inspecting node_modules, I discovered global.Whammy = (function(){ https://github.com/anti ...

What is the best way to integrate Halfmoon's JS from npm into my current code using Gulp?

I am eager to incorporate the Halfmoon framework into a personal project and have successfully downloaded it through npm. To utilize the example JavaScript provided on this page (found at ), I need to import the library using a require statement. var halfm ...

What is the correct way to invoke a static TypeScript class function in JavaScript?

Recently, I encountered a scenario where I have a TypeScript script called test.ts structured like this: class Foo { public static bar() { console.log("test"); } } The requirement was to call this TypeScript function from plain JavaScript ...