How to add an external JavaScript file to an Angular app? - javascript

So I followed the Angular tutorial, downloaded the example app and wanted to use my own javascript. I first tried importing it like usual with the tag in app.component.html, but that didnt work. What Im trying to achieve is a button, that just outputs "hello" to the console onclick with external javascript.
Code of the external js file:
function yep() {
console.log("hello");
}
With <button onclick="yep()"> and the script tag it didnt work, so i searched it up. Someone suggested to link the script file in scripts in angular.json, but that didtn solve it, I linked it b ut yep() is still undefined.

I wouldn't use Nicolar Stadler's solution - in Angular accessing DOM in ts code directly is a security vulnerability.
I linked the external file in angular.json, and it worked. In angular.json in
projects/#projectName#/architect/build/scripts I added
"scripts": ["src/assets/external.js"]
(that's the path to my external file). And I tried calling it in 2 ways, either yours:
<button onclick="yep()">
And more Angular way:
<button (click)="callYep()">
where callYep() is defined in the component:
callYep() {yep();}
where yep() is the external method, but it has to be declared for the typescript:
declare global { const yep: () => {}; }
And the external method was called both times on button click.

Works with following code:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'app';
loadScript(url) {
const body = <HTMLDivElement> document.body;
const script = document.createElement('script');
script.innerHTML = '';
script.src = url;
script.async = false;
script.defer = true;
body.appendChild(script);
}
ngOnInit() {
this.loadScript('../assets/scripts/index.js');
}
}

Related

How to force an Angular Component to load up external script in its template

I am a newbie working on a project. Some components in my app need external (third-party) scripts for some features to work properly, and all I just need to do is include, locally or via a CDN, the script via the tag in the HTML templates of the components. I've read so many questions on this platform and none of them has particularly addressed my use case:
I just want to add an external script tag like this: <script src="./assets/vendor/bla-bla-bla.min.js"></script> to my Component's template, and force Angular to be aware of the script and load them dynamically when ever I route to my Component. That's all!
Angular CLI 13.0.4,
npm 8.19.2,
node 18.12.1
here you can use this logic :
apiVariableNameHere is variable name or api from your url that needs to be called.
declare let apiVariableNameHere: any;
#Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
constructor(
private renderer: Renderer2,
) { }
ngOnInit() {
this.loadScript(yourUrl);
}
public loadScript(url) {
let node = document.createElement('script');
node.src = url;
node.type = 'text/javascript';
node.async = true;
node.charset = 'utf-8';
document.getElementsByTagName('head')[0].appendChild(node);
}
}

Add JavaScript library/code in Angular CLI

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';

How to use methods from external js in Angular

I need to call a function from external js file into my Angular component
I already go through the related question
How can i import external js file in Angular 5?
How to include external js file in Angular 4 and call function from angular to js
My External JS (external.js)
var radius = 25;
function calculateRadius(pi) {
let piValue = 3.14159;
if(pi) {
piValue = pi;
}
var result = piValue * radius * radius;
console.log('Result: ', result);
}
function wrapperMethod(pi) {
console.log('Hi, this is from wrapper method');
calculateRadius(pi)
}
I added the said JS file in the angular.json under scripts block
"scripts": [
"src/assets/external.js",
]
In the CircleComponent, I would like to call the method
import wrapperMethod from '../../src/assets/external.js';
#Component({
selector: 'app-circle',
templateUrl: './circle.component.html',
styleUrls: ['./circle.component.css']
})
export class CircleComponent implements OnInit {
constructor() { }
ngOnInit() {
wrapperMethod(3.14159);
}
}
But its failing to call the method. Kindly assist me how to achieve this.
Note: The said methods as just an example methods, I want to implement this logic with the complex code file. The said question tells about typings.d.ts, but I don't know where is typings.d.ts in my Angular project. Kindly brief me regarding this. If the said question gives good solution means, why should I post this question.
Angular Structure (Created using Angular CLI)
I don't know where is typings.d.ts, could anyone please tell me where is typings.d.ts - which is mentioned in the said questions How to include external js file in Angular 4 and call function from angular to js
You can follow this below steps
1) First add a reference of your external JS file for importing it to the component.
import * as wrapperMethods from '../../src/assets/external.js';
2) Now declare a "var" of the same name that your function has inside external JS.
declare var wrapperMethods: any;
3) ngOninit(){
wrapperMethods();
}
put your external .js file under scripts in build
if still can not see methods inside it put in in index.html
<script src="assets/PATH_TO_YOUR_JS_FILE"></script>
in your component after import section
declare var FUNCTION_NAME: any;
ANY_FUNCTION() {
FUNCTION_NAME(params);
}
Don't get confused with typings.d.ts. Follow below steps.
1.Add your external file inside assets folder. The content of this file will be by default included as per your angular-cli.json.
2.The function of your js which you're going to use must be exported. i.e.
export function hello() {
console.log('hi');
}
3.Import your file inside your component as below.
import * as ext from '../assets/some-external.js';
4.Now you can reference it like
ext.hello();
Steps:-
1. create a external js file.
2. In component.ts use the below code.
ngOnInit() {
this.loadJsFile(JsFilePath);
}
public loadJsFile(url) {
let node = document.createElement('script');
node.src = url;
node.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(node);
}
3. If u use jquery then define selector in html to render. Or store data in variable.
Make sure you have to add jquery cdn in index.html and you have to install Jquery and its types package from npm.

Inline js with Iframe src not working in IE11 with Angular

I have a scenario where i have to embed a inline js to an iframe src by dynamically building the iframe at runtime when the component loads.
The example runs fine in both Chrome and Edge but fails in IE11 , what could be the possible reason? IE dosen't even complain and if we check the console log nothing gets printed, where as in chrome it will print my name in the console log .
Stackblitz link.
Note - Please run the app in chrome as well as IE to see the difference .
import { Component, OnInit, Renderer2, ElementRef } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit{
name = 'Angular 6';
constructor(private renderer : Renderer2, private elRef : ElementRef ){}
ngOnInit(){
const outerDiv = this.elRef.nativeElement.getElementsByTagName('div')[0];
const el = this.renderer.createElement('iframe');
let script =encodeURI(`data:text/html,<script>console.log('DONE');var execute = function(context){ console.log(context.data.name);}; window.addEventListener('message', function(msg){execute(msg);});</script>`);
el.setAttribute('sandbox', 'allow-scripts');
el.setAttribute('src', script);
outerDiv.appendChild(el);
el.onload = function() {
el.contentWindow.postMessage({name: 'Rahul'}, "*");
}
}
}
<div></div>
Due to security reason in IE, you can not give base64 data of any image/ pdf or any other assets to a HTML object. Instead you can use path of the server having the asset.
how to display base64 encoded pdf?
This gives an example.

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

Categories

Resources