简体   繁体   中英

Adding JavaScript Chessboard Library to Angular Project

I am trying to set up a basic angular web page that displays a chessboard. I am using the chessboardjs library found here .

The instructions to initialize an empty chessboard as given by the website for the HTML and JS respectively are:

<div id="board1" style="width: 400px"></div>

var board1 = ChessBoard('board1', 'start');

In my typescript file, all I have so far is:

import { Component } from '@angular/core';
import { ChessBoard } from 'chessboardjs';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})

export class AppComponent {
    board1 = ChessBoard('board1', 'start');
}

When I load my web page, I get the following error:

ERROR TypeError: Object(...) is not a function

and the line it points to is where I use the ChessBoard function.

I have included the chessboard and @types/chessboard libraries through npm and have no compile errors.

Any guidance would be greatly appreciated in how I can include a javascript library in my Angular project.

angular.json

...

"scripts": [
      "call ChessBoard library here"
   ],
...

create new file types.d.ts in src directory

types.d.ts

declare const ChessBoard:any;

AppComponent should be

import { Component, AfterViewInit } from '@angular/core';
import * as ChessBoard from 'chessboardjs/www/js/chessboard';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements AfterViewInit {

  title = 'frontend';
  board1: ChessBoard;

  ngAfterViewInit() {
    this.board1 = ChessBoard('board1', {
      draggable: true,
      pieceTheme: 'node_modules/chessboardjs/www/img/chesspieces/wikipedia/{piece}.png'
    });
  }

}

Please make sure you added jQuery in the index.html or scripts of your angular.json file as well as node_modules/chessboardjs/www/css/chessboard.css in the stylesheets of your angular.json file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM