Add JavaScript library/code in Angular CLI - javascript

I am trying to use the Typed.js library in Angular CLI, but I couldn't manage to make it work. I followed the instructions in How can I use JavaScript code in Angular 7?: copied the jQuery library and typed scrips in assets folder, added a path to the files in angular.json, but I am not sure what to do in the component.ts file:
This is my component.ts code:
import { Component, OnInit } from '#angular/core';
declare var jQuery: any;
declare var Typed: any;
#Component({
selector: 'app-typing',
templateUrl: './typing.component.html',
styleUrls: ['./typing.component.scss']
})
export class TypingComponent implements OnInit {
constructor() { }
ngOnInit() {
var typed = new Typed('.typed', {
strings: ["First sentence.", "Second sentence."],
typeSpeed: 30
});
}
onComplete() {
}
}
I am pretty sure what I wrote in ngOnInit() is wrong, but how can I make it right?

You have to import typed.js in order to be able to use it. Declaring it as variable with type of any does not make any sense. Try importing it instead like this:
import Typed from 'typed.js';

Related

use JavaScript function in angular app.component.ts

i have a js file action.js and i want to use javaScript in angular. so when i read about it, it says that js file must be put in assets and the path must be refered in scripts array in angular.json and then using declare in ts and ngOnInit but this raises an error that the function is undefined beside that is forbidden to access the js file and MIME type checking is enabled
here is my js file function
function Di(){
console.log('ffffffffffffff');
}
the app.component.ts
import { AstMemoryEfficientTransformer } from '#angular/compiler';
import { Component, OnInit } from '#angular/core';
declare function Di(): any;
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit{
title = 'Calculator';
ngOnInit() {
Di();
}
}
angular.json
"styles": [
"src/styles.scss"
],
"scripts": ["src/assets/js/action.js"]
},
app.component.html
</div>
</div>
<script src = "/src/assets/action.js"></script>
</body>
thanks in advance
want to use js functions in angular
Try to create a di.ts file and export your function inside
export default function Di(){}
then import it into your AppComponent
import Di from 'di'
Create a ts file instead of js and then create your function like this
export fuction Di() { console.log('Di') }
then import it into your component.
If this works for you I would like you to inform me, please.
Not sure that I understand the sense of this function - should it be executed by click? Or with component creation?
Assuming that with on button click from html template,.you should add this fn as a public field into component and call it with parentheses from html

How to use cool-ascii-faces in Angular?

Just for fun, I'd like to use the javascript library cool-ascii-faces in my Angular application. I followed the instructions in the blog "How to use external JavaScript Libraries in Angular 8".
I did the following things:
installed cool-ascii-faces per npm in my Angular project under node_modules.
In angular.json, added these two scripts to both build and test section:
"scripts": [
"./node_modules/cool-ascii-faces/cli.js",
"./node_modules/cool-ascii-faces/index.js"
]
My app.components.ts looks like this:
import { Component, OnInit } from '#angular/core';
declare var coolFace: any;
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.sass']
})
export class AppComponent implements OnInit {
ngOnInit(): void{
console.log(coolFace());
}
}
But, in the console I only see: ReferenceError: coolFace is not defined. What have I done wrong?
Thank #Andres O. Serrano for his advice. I tried both approach, neither worked.
But I came up with another solution. Simply store all the ascii faces in a Json file under /asset. Then follow the instruction in the blog "How to Read Local JSON file in Angular". It works like a charm. Thanks!

Access function defines in JavaScript file from TypeScript file

I have a function X within a JavaScript file “MyFile.js” in the following path of an Angular 4 project : /assets/js/MyFile.js
I already added the path in the angular-cli.json into the scripts section.
...
“scripts”:
[ “assets/js/MyFile.js”]
...
Question: How can access the function X in MyFile.js from a typescript component?
I don't believe that you can call a function from a script added via .angular-cli.json, although you can implement IIFEs that way. Normal usage is for external libraries (bootstrap.js, collapse, animations and the like) as they get added as <script> tags in the index.html.
Rather than adding it to your angular-cli.json, it's easier to import it in your components
Give MyFile a .ts extension to avoid having to pass the --allowJs flag. E.g., MyFile.ts
Make sure to export your functions. If you have several, you might put them in a class and make them static (but that's a different question). Here's what I did:
_
// myfile.ts
export const myFunction = () => {
console.log('hello');
};
_
Import the script into the desired component via import { myFunction } from '../assets/js/myFunction'
_
import { Component, OnInit } from '#angular/core';
import { myFunction} from '../assets/js/myfile';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'app';
ngOnInit() {
myFunction();
}
}
_

Using JQuery Plugins in Angular 4 Applications

So I am currently trying to use some jquery plugins like Magnific-Popup etc in my Angular 4 application but I'm having some trouble. I installed jquery by doing npm install --save-dev #types/jquery in my terminal and that worked fine, but I'm having trouble getting the actual plugins to work. This is what I tried initially,
#Component({
selector: 'app-showcase',
templateUrl: './showcase.component.html',
styleUrls: ['./showcase.component.css']
})
export class ShowcaseComponent implements OnInit {
#ViewChild("elementRef") elref2: ElementRef;
constructor(private elRef: ElementRef) { }
ngOnInit() {
jQuery(this.elref2.nativeElement).magnificPopup();
}
ngAfterViewInit() {
}
In order to get typescript to recognize the magnificPopup() function, I tried importing the scripts from the magnificPopup documentation into my index.html (at the bottom of the body tag), but as far as I can tell that is not working. Webstorm says "can not resolve file jquery.magnific-popup.js". I'm also loading the jquery.min script as well, and that seems to work fine.
I also tried running npm-install magnific-popup, but that also failed. Additionally, I tried adding the script into the angular.JSON file but to no avail.
I guess what I'm asking is, what is and how can I go about installing and using a third-party jquery plugin like magnific-pop up into my angular 4 application?
Thanks, any help is appreciated.
I have an Angular project where I need to use (for now) a jquery dependent plugin (nanoscroller). I use angular-cli to do all my build processes and my angular-cli.json file has the following under the "scripts" property:
"scripts": [
"../node_modules/jquery/dist/jquery.js",
"../node_modules/nanoscroller/bin/javascripts/jquery.nanoscroller.js"
]
Then I use the plugin as follows:
import { AfterViewInit, Component, ElementRef, OnDestroy, Renderer, ViewChild } from "#angular/core";
declare var jQuery: any;
#Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.scss"]
})
export class AppComponent implements AfterViewInit {
layoutMenuScroller: HTMLDivElement;
#ViewChild("layoutMenuScroller") layoutMenuScrollerViewChild: ElementRef;
constructor() {
}
ngAfterViewInit() {
this.layoutMenuScroller = <HTMLDivElement>this.layoutMenuScrollerViewChild.nativeElement;
jQuery(this.layoutMenuScroller).nanoScroller({ flash: true });
}
// etc..
}
Perhaps you can adopt this to your use-case.

Injecting angular1 service in angular2 directive

I'm reading lots of articles on this matter like this, and this and also this but each one of these articles starts from a situation in which the NG1 service is a class and can be exported.
I'm in a very different situation, i often have multiple services in the same file and they are defined in a very old style manner like
angular.module('App.services').factory('SessionService',
function() {
var defer = $q.defer();
[...]
}
);
No class, no export.
And this stuff is directly linked in the page with an old fashioned <script src="...">
At the same time i'm trying to create new directives in Angular2 and these directives need those old fashioned services.
I get i should be able to write something like this
import {Injector,Component, Directive, ElementRef, Input, View} from 'angular2/core';
var injector = Injector.resolveAndCreate([
SessionService
]);
var SessionService = injector.get(SessionService);
#Component({
selector: 'nav-bar'
})
#View({
templateUrl: '/app/components/navbar/navBar.html'
})
export class navBar {
constructor() {
}
}
but of course SessionService object is not found.
How can i get out of this mess?
[Additional Info]
Using babel as transpiler
angular2-annotations plugin added
A great article to understand the difference between Annotations and Decorators in angular2: http://blog.thoughtram.io/angular/2015/05/03/the-difference-between-annotations-and-decorators.html
You simply need to leverage #Inject:
#Component({
selector: 'nav-bar'
templateUrl: '/app/components/navbar/navBar.html'
})
export class navBar {
constructor(private #Inject('SessionService') sessionService) {
}
}
See this plunkr for more details: http://plnkr.co/edit/U6ygjUUQ04mTGAAaC1pZ?p=preview
You can notice that with factory you can't use classes. It's only possible with services...
If you use ES6 only, you could try this:
#Component({
selector: 'nav-bar'
templateUrl: '/app/components/navbar/navBar.html'
})
export class navBar {
constructor(sessionService) {
}
static get parameters() {
return [[ new Inject('...'), new Inject('...') ]];
}
}

Categories

Resources