Angular - How To Import Javascript Into Angular Component
Solution 1:
You must first declare it in typing.d.ts and include angular.json script.
in angular.json
{
"build" : {
"scripts" : [
"node_modules/admin-lte/plugins/bs-stepper/js/bs-stepper.min.js",
....
]
in typing.d.ts
declare module 'admin-lte/plugins/bs-stepper/js/bs-stepper.min';
Note : If this is a JQuery package then you need to create an interface.
declare module 'jquery';
interface JQuery {
Stepper(DOM : any, options?: any): any;
}
finally you can now call it in the component.
in component
import Stepper from 'admin-lte/plugins/bs-stepper/js/bs-stepper.min';
Edit : Create a file named typing.d.ts
inside the src folder. then add
/// <reference path = "typings.d.ts" />
to the top of the src/main.ts
file
Solution 2:
As it happens there is a NPM package for bs-stepper
that could be used out-of-the-box with Angular.
1. Install the package
From the project root folder, run the command
npm install bs-stepper --save
Also install bootstrap
if needed
npm install bootstrap --save
2. Import the CSS
styles.css
@import '~bs-stepper/dist/css/bs-stepper.min.css';
/* Also import bootstrap if needed */
@import '~bs-stepper/dist/css/bs-stepper.min.css';
3. Use ViewChild
instead of querySelector
Using document.querySelector
in an Angular app would search the entire DOM whereas the element would only be present in the current component. Based on the size of the app it might incur a performance issue. Instead you could use the @ViewChild
decorator with with a template reference variable
Template (*.html)
<!-- Here, `bsStepper` is the template reference variable -->
<div #bsStepper id="stepper1" class="bs-stepper">
...
</div>
Component (*.ts)
import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
import Stepper from 'bs-stepper';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
@ViewChild('bsStepper', { static: false }) stepperElement!: ElementRef<any>;
public stepper!: Stepper;
next() {
this.stepper.next();
}
onSubmit() {
return false;
}
ngAfterViewInit() {
this.stepper = new Stepper(this.stepperElement.nativeElement, {
linear: false,
animation: true
});
}
}
Working example: Stackblitz
Post a Comment for "Angular - How To Import Javascript Into Angular Component"