Angular - How to import Javascript into Angular Component - javascript

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

Related

Adding OpenRouteService to Angular Application on Stackbliz

I added OpenRouteService to my Stackbliz application but cant get it working.
the Component looks like:
import { Component, OnInit } from '#angular/core';
import {Location} from '#angular/common';
import {Openrouteservice} from '/openrouteservice-js/dist/ors-js-client';
#Component({
selector: 'app-event-plan',
templateUrl: './event-plan.component.html',
styleUrls: ['./event-plan.component.scss']
})
export class EventPlanComponent implements OnInit {
constructor(private _location: Location) {
console.log("++++")
console.log(Openrouteservice)
}
ngOnInit() {
}
backClicked() {
this._location.back();
}
}
My problem is that it just doesnt get loaded. I added it as a dependency in the dependency section.
I made the project public here is the url - https://stackblitz.com/edit/angular-micwge?file=src%2Fapp%2Fevent-plan%2Fevent-plan.component.ts
You will have to change the way you import the library. The current way you import is looking for a named export from the library.
If you have allowSyntheticImports and esModuleInterop in your tsconfig.json use this:
import Openrouteservice from 'openrouteservice-js';
otherwise:
import * as Openrouteservice from 'openrouteservice-js';
Find your forked stacknlitz

Angular 7 add Javascript plugin

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

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

import code from javascript file inside typescript class

I have app.js file:
var app = angular.module('app', ['kendo.directives', 'ui.router', 'app.sysSettings', 'app.globalConstants',
'pascalprecht.translate', 'ngTouch', 'ngDialog', 'ngCookies']);
And I would like to reuse this variable ("app") inside my ts file.
My app.components.ts:
import { Component, Inject } from '#angular/core';
import { UpgradeModule } from "#angular/upgrade/static";
import { app } from '../../apps/login/app';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private upgrade: UpgradeModule,
private app_private: app.name) { }
ngOnInit() {
this.upgrade.bootstrap(document.body, [this.app_private]);
}
}
I imported import { app } from '../../apps/login/app'; , then added "app" to constructor and trying to use it inside ngOnInit function but getting error :
compiler.js:486 Uncaught Error: Can't resolve all parameters for AppComponent: ([object Object], ?).
at syntaxError (compiler.js:486)
at CompileMetadataResolver.push../node_modules/#angular/compiler/esm5/compiler.js.CompileMetadataResolver._getDependenciesMetadata (compiler.js:15706)
at CompileMetadataResolver.push../node_modules/#angular/compiler/esm5/compiler.js.CompileMetadataResolver._getTypeMetadata (compiler.js:15541)
at CompileMetadataResolver.push../node_modules/#angular/compiler/esm5/compiler.js.CompileMetadataResolver.getNonNormalizedDirectiveMetadata (compiler.js:15026)
at CompileMetadataResolver.push../node_modules/#angular/compiler/esm5/compiler.js.CompileMetadataResolver._getEntryComponentMetadata (compiler.js:15854)
at compiler.js:15335
at Array.map (<anonymous>)
at CompileMetadataResolver.push../node_modules/#angular/compiler/esm5/compiler.js.CompileMetadataResolver.getNgModuleMetadata (compiler.js:15335)
at JitCompiler.push../node_modules/#angular/compiler/esm5/compiler.js.JitCompiler._loadModules (compiler.js:34413)
at JitCompiler.push../node_modules/#angular/compiler/esm5/compiler.js.JitCompiler._compileModuleAndComponents (compiler.js:34374)
Does anybody have suggestions how to make property from javascript file be accessible inside typescript class?
In order to import an object from a file, it has to be exported using the export keyword. However, your angularjs app is defined in normal javascript files outside typescript so using export is not an option. So, to have access to it from typescript, first you have to bring it to typescript level and then you will be able to import it from your component.
So you can create the following ts file to import the app to typescript:
my-angularjs-app.ts
let angular = window['angular']; // to avoid typescript syntax error
export const app = angular.module('app');
app.component.ts
Then you can use it on your module like so:
import { app } from 'my-angularjs-app';
// ...
export class AppComponent {
constructor(private upgrade: UpgradeModule) { }
ngOnInit() {
this.upgrade.bootstrap(document.body, [app.name]);
}
}
Notice, you don't have to inject it on the constructor, the value is already there.

Use external lib with Angular

I want to use this lib in my app : https://www.npmjs.com/package/jquery-animated-headlines
But i don't know how to import it.
First, i add these lines in my angular-cli.json
"styles": [
...
"../node_modules/jquery-animated-headlines/dist/css/jquery.animatedheadline.css"
],
"scripts": [
...
"../node_modules/jquery-animated-headlines/dist/js/jquery.animatedheadline.min.js"
]
Second, i install jquery npm install jquery --save
Then, i import jquery : import * as $ from 'jquery';
Finally i copy/paste their example :
TS :
constructor () {
$(function() {
$('.selector').animatedHeadline();
})
}
HTML :
<div class="selector">
<h1 class="ah-headline">
<span>My favorite food is</span>
<span class="ah-words-wrapper">
<b class="is-visible">pizza</b>
<b>sushi</b>
<b>steak</b>
</span>
</h1>
</div>
I get this error : Uncaught TypeError: $(...).animatedHeadline is not a function
I don't know what i'm doing wrong ...
Thanks
You don't need to include your libs in angular.json. Import it just where u need it.
First, install the packages:
npm install jquery jquery-animated-headlines --save
Then, go to the desired component and import them:
import * as $ from 'jquery' // in case u haven't imported it globally.
import * as animatedHeadline from 'jquery-animated-headlines;
#Component()
...
constructor () {
$(document).ready(() => $('.selector').animatedHeadline())
}
Here is how I got it to work, but there must be a better way. I created a new project using #angular/cli version6.
npm install --save jquery jquery-animated-headlines
In the angular.json file, add "node_modules/jquery-animated-headlines/dist/css/jquery.animatedheadline.css" to the styles array.
Update the app.component.html to:
<h2 #foo>Here are some links to help you start: </h2>
app.component.ts
import { Component, AfterContentInit, ViewChild, ElementRef } from '#angular/core';
import * as jQuery from 'jquery';
import 'jquery-animated-headlines';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterContentInit {
#ViewChild('foo') fooElement: ElementRef<any>;
ngAfterContentInit(): void {
$(this.fooElement.nativeElement).animatedHeadline();
}
}
Now things should work at this point, but don't seem to due to the way that the plugin library is written. I also had to go into the node_modules/jquery-animated-headlines/dist/js/jquery.animatedhealdine.js file and update the way that it is importing jquery.
The file comes looking like:
(function($) {
.
.
.
}(jQuery));
and I had to update it to:
(function (factory) {
"use strict";
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
}
else if(typeof module !== 'undefined' && module.exports) {
module.exports = factory(require('jquery'));
}
else {
factory(jQuery);
}
}(function ($, undefined) {
.
.
.
}));
I'm not sure if there is a better way to handle this in Angular and this won't work well with an automated build system, but for local development it should work fine.
UPDATE
The way to get this working in your application is as follows.
In the angular.json file add:
"node_modules/jquery/dist/jquery.js",
"node_modules/jquery-animated-headlines/dist/js/jquery.animatedheadline.js"
to the scripts property.
In your component, use declare var $: any;. For example:
import { Component, AfterContentInit, ViewChild, ElementRef } from '#angular/core';
declare var $: any;
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterContentInit {
#ViewChild('foo') fooElement: ElementRef<any>;
ngAfterContentInit(): void {
$(this.fooElement.nativeElement).animatedHeadline();
}
}
GitHub repo.

Categories

Resources