Lucifer
Lucifer

Reputation: 516

How to add custom js file to angular component like css file

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

Answers (3)

Akash Agrawal
Akash Agrawal

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

andrea06590
andrea06590

Reputation: 1299

3 main steps to include js in angular

  • Add your script.js in assets/scripts and angular-cli package
  • In your js file in assets/scripts you must have window.initMethod = function() { ... your code ... }
  • In your component.ts declare let initMethod: any;

Upvotes: 0

user4676340
user4676340

Reputation:

You can't.

But, you can add it in your application as a global script by addiing it in angular-cli.jsonfile :

"scripts": [
  "assets/xxx.js", // path to assets file
  "../node_modules/moment/moment.js" // Path to node modules dependency
],

Upvotes: 0

Related Questions