How to Use External JavaScript Libraries in Angular 8
I will show how you can add an external JavaScript library that has JavaScript files, css files, and image files.
As an example we will add chessboard.js and JQuery to a new Angular project.
Create the Angular project:
ng new js-lib-example
Enter the js-lib-example directory
cd js-lib-example
Install chessboard.js
npm install chessboardjs --save
In your Angular project open the angular.json file locate the “assets”, “styles”, and “scripts” section. It appears in two locations in the angular.json file.
The first location is under this section:
The second location is under this section:
Add the path to the chessboard.js JavaScript, CSS, and image files to both sections:
Next we need to add the JQuery library because chessboard.js depends on JQuery.
Install JQuery
npm install jquery --save
In your angular.json file locate the “assets”, “styles”, and “scripts” section again. Add the JQuery JavaScript file to both sections like you did above:
And add it to the other section in your angular.json file:
We are ready to use chessboard.js in our project. Open your app.component.ts and add the following code:
Next open your app.component.html add add this html:
If you haven’t run npm start or ng serve already go ahead and run it now:
npm start
or
ng serve
In your browser go to http://localhost:4200 and you will see the chess board. You can drag and drop the pieces:
FYI, chess logic is not part of the chessboard.js library. It’s only a UI. If you want to add chess logic visit chess.js