0

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)
1
  • Are you thinking of building a Countdown Timer, like this? Commented Jan 17, 2019 at 13:42

3 Answers 3

1

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
} 

}
Sign up to request clarification or add additional context in comments.

Comments

0

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($);
    }
}

Comments

0

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($) 
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.