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)
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
}
}
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($);
}
}
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($)
}
Related
I have this error:
Type {...} is missing the following properties from type 'any[]': length,pop,push,concat, and 28 more
I'm assigning album variable to the albumData array. Here is the code:
import { Component, OnInit } from '#angular/core';
import albumData from '../data/SearchResultsAlbum.json';
#Component({
selector: 'app-album-component',
templateUrl: './album-component.component.html',
styleUrls: ['./album-component.component.css']
})
export class AlbumComponentComponent implements OnInit {
album:Array<any>=[];
constructor() { }
ngOnInit(): void {
this.album=albumData;
}
}
What am I doing wrong? Thank you in advanvce!
album:any=[];
use this code instead of the code you have added
By default, Angular doesn't read the JSON file in the application. So we need to do some extra stuff for that. So we will create a file named 'json-typings.d.ts' inside the app folder of the project.
declare module "*.json" {
const value: any;
export default value;
}
source: https://jsonworld.com/demo/how-to-read-local-json-file-in-angular
In my Angular-11, I have this Javascript file:
"node_modules/admin-lte/plugins/bs-stepper/js/bs-stepper.min.js",
I added it to angular.json as shown above.
import Stepper from '...';
#Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
name = 'Angular';
private stepper: Stepper;
next() {
this.stepper.next();
}
onSubmit() {
return false;
}
ngOnInit() {
this.stepper = new Stepper(document.querySelector('#stepper1'), {
linear: false,
animation: true
})
}
}
How do I import it into this component: profile.component.ts this way,
import Stepper from '...';
from the Javascript path
Thanks
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
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
My intention is to add a javascript plugin, namely this one:
https://steven.codes/typerjs/
So far, my approach was to add its JS file in my assets folder and added the path to angular.json.
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"src/assets/js/typer.js"
]
My next step was to declare a var in the component and to try to call it in ngOnInit().
import {Component, OnInit} from '#angular/core';
import * as AOS from 'aos';
declare var Typer: any;
#Component({
selector: 'app-background',
templateUrl: './background.component.html',
styleUrls: ['./background.component.scss']
})
export class BackgroundComponent implements OnInit {
rotate = false;
constructor() { }
ngOnInit() {
this.rotate = !this.rotate;
AOS.init();
Typer.init();
}
}
I don't get any errors, but it's not working. Does somebody know a working approach?
There are multiple options that may help.
First - Node style require:
var typer = require("typer");
Second one use it like you already did with aos:
import * as typer from 'typer';
In this case you must be sure that your .js lib can be found. You have added it to angular.js so that should works.
In both cases the initialization should be the same:
ngOnInit() {
this.rotate = !this.rotate;
AOS.init();
typer.init();
}
I am new to Angular and Materialize. I am trying to initialize a carousel within my Angular component.
Materialize mentions three ways:
M.AutoInit();
or
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.carousel');
var instances = M.Carousel.init(elems, options);
});
or
$(document).ready(function(){
$('.carousel').carousel();
});
I have installed Materialize via node. I have both its CSS and JS as dependencies in my angular.json folder. The CSS styling works. I have tried these three methods within my ngOnInit lifecycle hook within my component. "M" is not recognized. I tried importing materialize:
import { materialize } from '../../../node_modules/materialize-css'
and
let m = materialize;
But this hasn't worked either.
I then installed jquery as a depedency and tried that method, but that doesn't seem to work either.
You should use the Materialize for Angular library. Asking how to use jQuery with Angular can get you a lot of downvotes.
https://www.npmjs.com/package/angular2-materialize
import OnInit from #angular/core library
declare const M: any; underneath imports
fire the M.AutoInit() function in ngOnInit() lifecycle hook
Example (where the component name is MediaComponent):
import { Component, OnInit } from '#angular/core';
declare const M: any;
#Component({
selector: 'app-media',
templateUrl: './media.component.html',
styleUrls: ['./media.component.scss']
})
export class MediaComponent implements OnInit {
constructor() { }
ngOnInit() {
M.AutoInit();
}
}
import { Component, OnInit } from '#angular/core';
declare var M: any;
I have a problem. Im creating an app in Angular2 using Semantic UI. In the documentation said that you can create a sortable table. it say that you have to import a tablesort.js and call $('table').tablesort() when the DOM is ready.
My problem start when it doesnt recognize that .tablesort is a method. It say that its not a method from Jquery so i dont know how to do work correctly
Here is my code:
import { Component, OnInit } from '#angular/core';
import { UserService } from "services/user.service";
import { Bet } from "models/bet";
import * as $ from 'jquery';
#Component({
selector: 'history',
templateUrl: 'history.component.html',
styleUrls: ['./history.component.css'],
})
export class HistoryComponent implements OnInit {
url: string;
bets = [];
constructor(private userService: UserService) {
this.url = 'http://localhost:3000/bets/history';
}
ngOnInit(): void {
this.userService.getHistory(this.url).subscribe(this.sucess.bind(this), this.error);
$('table').tablesort();
}
}
And in my index im importing:
<script type="text/javascript" src="semantic/components/tablesort.js"></script>
How can i do that Jquery recognize a external JS and can use the function from that JS.