Guide on incorporating the handsontable library with Angular 2

As I delve into the realm of configuration in npm, I am attempting to integrate the handsontable library into an Angular 2 project built with angular-cli (ng init). I have included the TypeScript definition for the library as well.

Below is the content of my app.component.ts file:

import { Component } from '@angular/core';
import 'handsontable/dist/handsontable.full.js';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';
  ngOnInit() {
  }
  ngAfterViewInit() {
    const myData = [
            ["1", "2", "3", "4", "5", "6"]
        ];

        const config = {
            data: myData,
            colHeaders: ['A', 'B', 'C', 'D', 'E', 'F'],
            startRows: 5,
            startCols: 5,
            minSpareCols: 1,
            //always keep at least 1 spare row at the right
            minSpareRows: 1
            //always keep at least 1 spare row at the bottom,
        };
        (<any>$("#test")).handsontable(config);
  }
}

Within app.component.html:

<h1>
  <div id ="test"></div>
</h1>

Contents of index.html:

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>AngularStart2</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root>Loading...</app-root>
</body>
</html>

Details from tsconfig.js:

{
  "compilerOptions": {
    "baseUrl": "",
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": ["es6", "dom"],
    "mapRoot": "./",
    "module": "es6",
    "moduleResolution": "node",
    "outDir": "../dist/out-tsc",
    "sourceMap": true,
    "target": "es5",
    "typeRoots": [
      "../node_modules/@types"
    ]
  }
}

Encountering the error:

ReferenceError: Handsontable is not defined at r.fn.init.$.fn.handsontable (http://localhost:4200/vendor.bundle.js:87583:26) at AppComponent.ngAfterViewInit (http://localhost:4200/main.bundle.js:79:20)

Attempted to import in the following manner as well:

import {Handsontable} from 'handsontable';

Resulting in the error:

Uncaught Error: Cannot find module 'numbro'
    at newRequire (handsontable.js:53) [<root>]
    at :8000/vendor.bundle.js:102461:16 [<root>]
    at Object.23.cellTypes (handsontable.js:4439) [<root>]
    at newRequire (handsontable.js:58) [<root>]

Having exhausted all solutions from https://github.com/handsontable/handsontable/issues/3627

Answer №1

As of now, HandsOnTable does not offer official support for Angular 2. For more information, you can check the Forum reference here. Support for Angular 2 is planned for Q1 of this year. If you would like to show your support for this feature, you can vote for it here.

Therefore, if you want to use HandsOnTable in an Angular2 app, you will need to include the HandsOnTable js & css files directly, like this-

Step1: Add these 2 lines to Index.html-

<link rel="stylesheet" href="http://docs.handsontable.com/0.30.1/bower_components/handsontable/dist/handsontable.full.css">

<script src="http://docs.handsontable.com/0.30.1/bower_components/handsontable/dist/handsontable.full.js"></script>

Step2: Your Sample AppComponent.ts should resemble this-

import { Component, AfterViewInit } from '@angular/core';

declare var Handsontable: any;

@Component({
    selector: 'my-app',
    template: `
<h3>Angular2 Final 2.0.0</h3>
<h2>Handsontable Performance Test (10000x100)</h2>

<div id="example"></div>
    `
})

export class AppComponent implements AfterViewInit { 

container: any;
hot: any;

ngAfterViewInit() {
this.container = document.getElementById('example');

this.hot = new Handsontable(this.container, {
  data: Handsontable.helper.createSpreadsheetData(10000, 100),
  rowHeaders: true,
  colHeaders: true,
  // performance tip: set constant size
  colWidths: 80,
  rowHeights: 23,
  // performance tip: turn off calculations
  autoRowSize: false,
  autoColSize: false,
});

}

}

Result Output:

https://i.sstatic.net/3Jrcl.png

Important: I am using Angular2 Final version 2.0.0

Answer №2

Thank you for the quick response,

@TSW I attempted to install both packages "numbro" and "pikaday" but unfortunately, it did not work as expected.

@Sanket, I appreciate your solution. However, I am using Angular CLI and I discovered that adding the following snippet in angular-cli.json resolves the issue:

"scripts": [
            "./../node_modules/jquery/dist/jquery.min.js",
            "./../node_modules/handsontable/dist/handsontable.full.min.js"
        ],

Is it possible to import handsontable by simply declaring it in package.json, as handsontable usually downloads numbro and pikaday on its own? Why is there a need to specifically use "handsontable.full.min.js"?

Answer №3

At the moment, this response does not directly address our question. However, there are plans in place to release an official wrapper for Angular 2+ in June. You can track the progress of this development here.

Update (August 29, 2017): We have seen some advancements in the creation of the official Angular2+ wrapper. You can follow the progress on the project here.

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

Troubleshooting issue with absolute paths in Vite project using React and TypeScript

I'm having trouble implementing absolute paths in a Vite react-ts project. This is how I set up the project: npm init @vitejs/app npx: installed 6 in 1.883s √ Project name: ... test-vite √ Select a framework: » react √ Select a variant: » rea ...

Deprecated: Using `-- (empty)` with `npm ls gulp-util` now returns a warning

I've been attempting to compile my Vue assets for a while now, encountering errors along the way. I updated node and npm to their stable and latest versions respectively, yet I'm facing a gulp problem. Recently, when trying to NPM install, an er ...

Is there a need to manually install npm packages yourself?

Currently, I am delving into the world of protractor and following a tutorial on Github. After successfully downloading protractor and proceeding with webdriver-manager update I encountered a failure which includes errors such as: downloading http://se ...

Exploring the TypeScript handbook: Utilizing rootDirs for Virtual Directories

Exploring the concept of Virtual Directories with rootDirs in the handbook, we find an interesting example demonstrating how modules can be imported from different source folders by combining multiple rootDirs. // File Structure src └── views ...

The data passed into the child component via Input() retains its original value even after being modified within the child

While passing an object containing data length and an array of objects to a child component, I noticed a strange behavior. Even after changing the data in the child component and reloading the page, the edited property still persists. To visualize this is ...

Encountered a npm protocol error following the execution of the yo hubot

I've been working on this issue for the past day. I am using ubuntu/trusty64 on virtual box through vagrant. Whenever I attempt to scaffold a new hubot project using the yo hubot command, hubot gets installed but encounters npm errors. The root of thi ...

Unable to bring in openai on Node.js

I recently installed Node version 16.13.1 and globally installed the openai package using 'npm install -g openai'. In my script, I imported the necessary packages like this: const { Configuration, OpenAIApi } = require('openai') Howeve ...

Performing calculations on two properties of an observable object in Angular 8 and then storing the result in a new property

Looking for guidance on how to display the sum of two properties from an observable data. Take a look at the code below and let me know your thoughts: Typescript class export class Amount { Amount1: number; Amount2: number; Total:number; } In typescript ...

What could cause my arguments to "not align with any signature" of console.log?

Here is a basic class example: export class Logger { constructor(private name: string) {} debug(...args: any[]) { console.debug(...args) } log(...args: any[]) { console.log(...args) } } Despite being able to pass anything to console.l ...

What events can cause all store states to be loaded when the page is altered?

I am currently utilizing ngrx/store, ngrx/effects, and ngrx/router. The implementation of my effects is structured as follows: @Effect() loadOneProduct$ = this.updates$ .whenAction(LOAD_ONE_PRODUCT) .switchMap(() => this.productService.loadOn ...

define` module root path

Currently, I am working with Typescript and my source files are located in the src directory. After transpiling, Typescript generates the output in the lib folder. This means that when I need to import components from my package, I have to specify the full ...

Updating from Gatsby version 4 to version 5

Currently, I am utilizing an Apple M1 Max processor with MAC os Ventura 13.0. My Node version is v18.12.1 and npm version is 8.19.2. Upon executing the following: gatsby new and configuring the site, Gatsby updated to version 4 and React to 18.1.0. Foll ...

"Implemented a fresh pathway within the app-routing.module.ts file, but unfortunately, ngxAdmin is experiencing functionality issues

While customizing the ngx-admin template, I attempted to incorporate a new module into the app module and added its route in app-routing.module.ts. However, upon trying to open it, the module seems to be stuck at loading without any errors appearing in the ...

Is it possible to enter NaN in Vue3?

Is there a way to handle NaN values and keep a field blank instead when calculating margins with a formula? https://i.stack.imgur.com/JvIRQ.png Template <form> <div class="row"> <div class="mb-3 col-sm ...

"Troubleshooting installation errors when installing Node.js Express dependencies through npm

I'm diving into the world of node.js and currently following this useful tutorial After successfully completing steps 1-4, I encountered errors when running the npm install command in step 5. You can view the errors in image 1 here: https://i.sstati ...

Service in Angular2 designed to retrieve JSON data and extract specific properties or nodes from the JSON object

Currently, I am trying to teach myself Angular2 and facing some difficulties along the way. I am working on creating a service that loads a static JSON file. Right now, I am using i18n files as they are structured in JSON format. The service will include a ...

Why isn't my event handler triggering when working with TypeScript services and observables?

I am currently working on a project in Angular 2 where I am incorporating observables and services in typescript. However, I have encountered an issue where the event handler in my observable is not being triggered. Below is the code snippet: The Service ...

Incorporating a TypeScript module into a JavaScript module within a React application

I'm encountering an issue with my React app that was created using create-react-app. I recently added a Typescript module to the project, which is necessary for functionality reasons. Although it will remain in Typescript, I made sure to install all t ...

Is there a way to transform the SmartyStreets' jQuery.LiveAddress plugin into its JavaScript SDK?

My website currently utilizes the jQuery.LiveAddress plugin, however, it was deprecated and subsequently removed by SmartyStreets back in 2014. <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <s ...

encountering difficulties while trying to install packages using npm

I encountered some issues while setting up a react-app and attempted to resolve them by deleting /node-modules and reinstalling, but the problems persist. I'm using Ubuntu as my operating system. Can someone assist me with this? Below is the error log ...