How to add JQuery in a DotNet generated Angular project? - javascript

I've to do some initialization for my theme after the view has been initialized.
I've implemented AfterViewInit, I've managed to import jquery:
import * as $ from 'jquery';
But now I need to execute this:
ngAfterViewInit() {
$(document).trigger('nifty.ready');
}
And I've trouble, because it seems that at this point, document is not known. I guess I should have another import, but I can't find from where?
My whole app.component.ts:
import { Component, AfterViewInit } from '#angular/core';
import * as $ from 'jquery';
#Component({
selector: 'app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
ngAfterViewInit() {
$(document).trigger('nifty.ready');
}
}
The error I get:
Exception: Call to Node module failed with error: TypeError: Cannot
read property 'document' of undefined at module.exports.module.exports
(E:\My\Clients\AppClientApp\dist\vendor.js:12879:12) at
AppComponent.ngAfterViewInit
EDIT
You can find here the whole web app part.
EDIT2
In fact I've the impression that jquery is not initialized properly at all, once loaded(without error), window.jquery return undefined... any idea why?

You can inject the document in your component.
https://angular.io/docs/ts/latest/api/platform-browser/index/DOCUMENT-let.html
import { Component, AfterViewInit, Inject } from '#angular/core';
import {DOCUMENT} from "#angular/platform-browser";
#Component({
selector: 'app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
constructor(#Inject(DOCUMENT) private document) {
}
}

Instead of importing jquery try this -
declare var jQuery:any;
jQuery(document);
console.log jQuery(document) to be sure
P.S make sure jquery is available on the window scope!

I took a look to your project. Well, I didn't test all the .Net features, but I guess your webpack config misses a plugin provider for jQuery (used to be done by angular-cli).
So you ever done :
npm install jquery --save
Try this :
npm install #types/jquery --save-dev
And then add the jquery plugin provider to your webpack.config.js :
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
]
Finally import it as follow :
import "jquery";
declare var $: any;

Related

Import js script to Angular from URL

i am building an app with angular but found a problem I don't know how to solve.
I need to import a js script and it has to be imported from the internet. (because these are their rules, so that they can do hotfixes)
The problem is, when I import the script into my index.html I can only use it in js files not in the typescript files. How can i use the libary in my ts files?
I can't install it via npm and i also can't download the file and add it to my project folder.
The libary is the airconsole API (https://developers.airconsole.com/#!/api)
Thanks for your help
it's only add in your component declare var AirConsole to use it, a fool Component
import { Component, VERSION } from '#angular/core';
declare var AirConsole //<--this is the "magic"
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular ' + VERSION.major;
airConsole=new AirConsole() //<--now you can use airConsole in your component
}
Update Well, generally we can use a service to mannage the airConsole, this allow us that all components that inject the service can use the functions,variables,...
Disclamer: I don't know about "AirConsole", so I imagine control it like we can control others .js like Cordova)
As we need that Angular know when a function is executed in .js, our service can be like
import { Injectable,NgZone } from '#angular/core';
declare var AirConsole;
#Injectable({
providedIn: 'root',
})
export class AirConsoleService implements OnInit {
airConsole=new AirConsole()
message:Subject=new Subject<any>();
constructor(private ngZone: NgZone) { }
ngOnInit(){
this.airconsole.onMessage = (from, data)=>{
this.ngZone.run(() => {
this.message.next({from:from,data:data})
});
})
}
message(device:any,message:any){
this.ngZone.run(() => {
this.airConsole.message(device,message);
});
}
}
So, e.g. you can subscribe to airConsoleService.message

External .js file in an Angular 8 project

I'm trying to call a function in a .js file from an Angular component, but I get the error "ERROR ReferenceError: myTest is not defined at TechnologiesComponent.onClick".
I have followed the steps described here, so I have created a file called custom.js in my src folder.
The file contains the following:
function myTest() {
alert('Welcome to custom js');
}
$(function() {
alert('Hello, custom js');
});
I have added the script in the scripts array in my angular.json, like so:
"tsConfig": "tsconfig.app.json",
"aot": false,
"assets": [
"src/assets"
],
"styles": [
"src/styles.css"
],
"scripts": ["src/custom.js"]
},
The .ts file where I want to use the .js file looks like this:
import { Component } from '#angular/core';
declare const myTest: any;
#Component({
selector: 'app-technologies',
templateUrl: './technologies.component.html',
styleUrls: ['./technologies.component.css']
})
export class TechnologiesComponent {
onClick() {
myTest();
}
}
A button is added to my template:
Click Me
When the button is pressed, the error "ERROR ReferenceError: myTest is not defined at TechnologiesComponent.onClick" is thrown. Why?
declare your function as a variable (in JS both are same)
custom.js
myTest = function(){
alert('Welcome to custom js');
}
also, verify if the script is getting imported in the final build
you may need to re-build if you are using ng serve
If you want to use code from .js files in .ts files you should use export and import.
Example with your project:
custom.js
export function myTest() {
alert('Welcome to custom js');
}
app.component.ts
import {Component} from '#angular/core';
import * as custom from 'src/custom.js';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
onClick() {
custom.myTest();
}
}
take note of line import * as custom from 'src/custom.js';
It's one of the best ways to import smth from non-ts files.
Structure:
I am using angular 10 and trying to access plane js file and It's not allow to change js file
i.e. can't able to add export in it
add your js files in angular.json
I want to access print() function in angular from myJs.js and which is like
// MyJS.js
function print(a){
cosole.log(a +" Code from JS");
}
app.component.ts
import {Component} from '#angular/core';
// following variable name and function name in js file should be same
declare var print: any;
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
onClick() {
print('Yes');
}
}
and fire ng serve again
( If still not work for you then try to put your js file in assets folder and change the path in angular.json)

How to Use External Javascript in TypeScript Angular

I want to use jquery and easypiechart js file's functions in typescript.
It doesn't work this way.
How to define these script what i specified in code as typescript ?
index.component.ts
import { Component, OnInit } from '#angular/core';
import * as $ from "../../../../../assets/plugins/jquery/jquery.min.js";
import { easyPieChart } from "../../../../../assets/plugins/easypiechart/jquery.easypiechart.min.js";
// these above 2 js files are defined in angular.json script section
#Component({
selector: 'app-index',
templateUrl: './index.component.html',
styleUrls: ['./index.component.scss']
})
export class IndexComponent implements OnInit {
constructor() {}
ngOnInit() {
//$(function(){
// $('.easypiechart').easyPieChart();
//});
// How to write this above script as typescript ?????????????????????
}
}
From the above question,it looks like jquery.easypiechart.min.js is the one that you need to use in your angular application as external js.
Put the js under assets folder say /assets/js/jquery.easypiechart.min.js
Goto your projects angular.json file and under scripts node of architect node put as an entry in the array.
"scripts": [
"./node_modules/jquery/dist/jquery.min.js",
"./src/assets/js/jquery.easypiechart.min.js" ]
Now you can refer the external js in any of your projects components
declare var $: any;// referencing jQuery library
#Component({
selector: 'app-index',
templateUrl: './index.component.html',
styleUrls: ['./index.component.scss']
})
export class IndexComponent implements OnInit {
constructor() {}
ngOnInit() {
$(document).ready(function () {
//accessing easypiechart.min.js.
$('.easypiechart').easyPieChart();
});
}
}
If you have included them in the scripts or index.html, you don't have to import them to the .TS file again
Use declare instead and it should work
What does 'declare' do in 'export declare class Actions'?
Instead of putting it in asset folder you should use it as node_modules dependency
For easy pie chart run this npm i easy-pie-chart --save & for jquery run npm i jquery
Normally you don't want to use jquery in Angular, because it usually implies to modify directly the DOM, which is a bad practice, but there is the way to do it: https://medium.com/all-is-web/angular-5-using-jquery-plugins-5edf4e642969
If you wanna plot a pie chart or other types of charts, you could use ng2-charts instead, it will allow you to use charts.js with Angular and Typescript.

How to use json2html with jquery within Angular?

I'm tasked with integrating an existing UI into another already existing Angular app and got hung up on this...
I know the data + transform works well outside of the Angular context.
I didn't see an npm package for the jquery json2html so I tried to import that part in an ad-hoc manner by saving it along side the component's directory.
It produces ERROR TypeError: $(...).json2html is not a function...
...
import * as $ from 'jquery';
import json2html from 'json2html';
import * from './jquery.json2html.min.js';
...
$('#myTable > tbody').json2html(data,transform);
before anything you have to add jQuery in your angular.json then in the component you would to use jQuery with it do so
....
declare let $: any; // you can use "jQuery" keyword instead of "$"
#component({
selector: '...',
templateUrl: ['...'],
styleUrls: ['...']
})
export class JqueryExampleComponent implements onInit {
constructor(private eleRef: ElementRef) {}
ngOnInit() {
$(this.eleRef.nativeElement).find('#myTable > tbody').json2html(data,transform);
}
}
when you use $(this.eleRef.nativeElement) that gonna get the tree root of the component dom then .find('selector') to get the element you want
npm install node-json2html
...
import json2html from 'json2html';
import * as $ from 'node-json2html';
...
ngAfterViewInit(){
$('table#myTable > tbody').json2html(data,transform);
}
or,
...
import json2html from 'json2html';
import * as $ from './jquery.json2html.min.js';
...
$('table#myTable > tbody').json2html(data,transform);
Link:- http://www.json2html.com/

Angular4/5 dependency injection docs not working

https://angular.io/guide/architecture#services
I'm following the docs on angular.io to inject dependencies like services, etc. I did everything they said and when I try to run it, the console keeps telling me:
Uncaught ReferenceError: LedgerService is not defined
I am doing nothing crazy except creating a simple component with a service where both constructors have console.log commands (constructors in both the component and service). I've done everything Angular says to do in their 2 paragraphs that details this feature of Angular.
The component itself is being injected into the main app module (with the service being injected into the component) and both the component and service were created with the Angular CLI. So there isn't much I've even done at all minus trying to inject the service. So I'm not sure where it is going wrong but it is definitely not working and just shows a blank page (when it previously had basic content by default).
I created both units, tried to specify providers in both the app.module and the component.ts file and neither works and yields the same error--when Angular claims either could work. I've also specified it as a private service within the constructor of the component.ts file.
Everything I've seen relating to this is always for Angular 1 or 2. Neither of which are even remotely similar to Angular 4/5.
If you really want to see this code, fine but it's literally just framework and nothing else:
bookkeeper.component.ts:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-bookkeeper',
templateUrl: './bookkeeper.component.html',
styleUrls: ['./bookkeeper.component.css'],
providers: [LedgerServiceService]
})
export class BookkeeperComponent implements OnInit {
constructor(private service: LedgerServiceService) { }
ngOnInit() {
console.log("Ledger component works!");
}
}
app.module.ts:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { InterfaceComponent } from './interface/interface.component';
import { BookkeeperComponent } from './bookkeeper/bookkeeper.component';
#NgModule({
declarations: [
AppComponent,
InterfaceComponent,
BookkeeperComponent
],
imports: [
BrowserModule
],
providers: [
LedgerServiceService
],
bootstrap: [AppComponent]
})
export class AppModule { }
ledger-service.service.ts:
import { Injectable } from '#angular/core';
#Injectable()
export class LedgerServiceService {
constructor() {
console.log("wtf");
}
}
LedgerService is actually called LedgerServiceService because I initially created LedgerService manually and then tried to use the AngularCLI to generate a service and named it LedgerService and it created a service called LedgerServiceService. Naming is not what is wrong. I only initially called it simply LedgerService because I figured it would be confusing.
Your examples are missing the import.
Anywhere we use a custom type, we also need to import that type.
For that reason, in both the module and component you will need to add:
import { LedgerServiceService } from './your-path-here'
You can see this in the examples they give on https://angular.io/guide/dependency-injection

Categories