Reputation: 516
I am new to angular. Can anyone say how can I add custom js file in angular template.
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
UPDATED
i want to add the below code
$("#single-slider").owlCarousel({
navigation: true,
slideSpeed: 600,
autoPlay: 6000,
singleItem: true,
pagination: false,
navigationText: [
"<i class='fa fa-angle-left'></i>",
"<i class='fa fa-angle-right'></i>"
],
});
Upvotes: 1
Views: 2240
Reputation: 2299
You can add a <script>
in your HTML but IT WON'T WORK because while building the app the Angular DOMSantizer removes all the <script>
.
So you have to load the custom js the way @trichetriche showed. But, if the js is required only for one component then there's a workaround which is kind of hacky.
You can load the js just after the DOM has been loaded/initialized in the ngAfterViewInit()
. This way Angular DOMSantizer doesn't know about the <script>
.
Here you go:
constructor(private elementRef:ElementRef) {};
ngAfterViewInit() {
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "../path-to-your-js-or-external-URL";
this.elementRef.nativeElement.appendChild(s);
}
For more info, refer this: https://github.com/angular/angular/issues/4903
Upvotes: 2
Reputation: 1299
3 main steps to include js in angular
Upvotes: 0
Reputation:
You can't.
But, you can add it in your application as a global script by addiing it in angular-cli.json
file :
"scripts": [
"assets/xxx.js", // path to assets file
"../node_modules/moment/moment.js" // Path to node modules dependency
],
Upvotes: 0