Karan
Karan

Reputation: 1118

Load multiple scripts in Component

I am new to angular 6. I just start learning angular 6. While creating a project i am stuck into error.

I am simply adding external scripts into my component and getting error

Here is my code

import { Component, OnInit } from '@angular/core';
import * as $ from 'src/assets/js/jquery-3.2.1.min.js';
import 'src/assets/js/countdowntime.js';

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

export class ComingsoonComponent implements OnInit {

  constructor() { }

  ngOnInit() {
     console.log($) // here is am getting output
  } 

}

Error:

Uncaught ReferenceError: jQuery is not defined at Object..
/src/assets/js/countdowntime.js (countdowntime.js:92)

Upvotes: 0

Views: 424

Answers (3)

prakash r
prakash r

Reputation: 113

Solution 1 : Use Jquery types

Need to add types for jquery version. you can find jquery types here

https://www.npmjs.com/package/@types/jquery

As typescript is strongly typed For all items which we use in a component should have types

Solution 2 :

create a variable $ and assign its type to any

A workaround if you're not able to find type for the current jquery version which is

declare var $: any;
@Component({
  selector: 'app-comingsoon',
  templateUrl: './comingsoon.component.html',
  styleUrls: ['./comingsoon.component.css']
})

inside your component life cycle check the value of the dollar, you will find jquery properties and method. Your error will be resolved

ngOnInit() {
  console.log($) 
} 

Upvotes: 0

amphetamachine
amphetamachine

Reputation: 30595

You should be able to add jquery as a package and reference it in your component code, so it can get picked up by Webpack:

$ npm add jquery

Then inside your TypeScript code:

import * as $ from 'jquery';

...

export class FooComponent implements OnInit {
    ngOnInit() {
        console.log($);
    }
}

Upvotes: 0

Sneha Pawar
Sneha Pawar

Reputation: 1127

Update your code

Add jQuery to your index.html or angular.json file

import { Component, OnInit } from '@angular/core';
declare var jQuery:any;
@Component({
  selector: 'app-comingsoon',
  templateUrl: './comingsoon.component.html',
  styleUrls: ['./comingsoon.component.css']
})
export class ComingsoonComponent implements OnInit {

constructor() {
   // load countdown 
     var c = document.createElement("script");
     c.type = "text/javascript";
     c.src = "src/assets/js/countdowntime.js";
     document.getElementsByTagName("head")[0].appendChild(c);
}

ngOnInit() {
  console.log(jQuery) // here is am getting output
} 

}

Upvotes: 1

Related Questions