use JavaScript function in angular app.component.ts - javascript

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

Related

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!

Angular 7 Dynamic variable name for imported component

In a simple angular app, I have created a test component like the one below:
test.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'test',
template: `<h1>I am a test</h1>`,
styles: [`h1 { font-family: Lato; }`]
})
export class TestComponent {
}
which I import in my app module like this:
app.component.ts
import { Component } from '#angular/core';
import { TestComponent } from './test.component';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
public TestComponent = TestComponent;
dynamic = "Test";
constructor(){
console.log(TestComponent);
console.log(this.TestComponent);
console.log(this['TestComponent']);
console.log(this[this.dynamic + 'Component']);
}
}
Getting help from this topic Angular 5 Dynamic variable name, I was able to get my component name dynamically (in the real example, the dynamic variable changes depending on an API call response).
My question is if there is any way to achieve the same result without having to pass the component as a local class variable, thus avoiding this line
public TestComponent = TestComponent;
without the this keyword the dynamic variable is not working, it gives me an error
console.log([this.dynamic + 'Component']);
I tried adding the code in a stackblitz but cannot seem to be able to share it (https://github.com/stackblitz/core/issues/215), but it is quite simple to copy the two files in a new empty stackbitz (https://stackblitz.com/edit/angular-f4ars5) to replicate.
Thanks in advance.
First you need to understand the following line
this['TestComponent']
In javascript you can access class properties in two ways. Class.property or Class["property"]. So when you are writing this["TestProperty"] you are effectively saying, Get AppComponentInstance.TestProperty
So console.log([this.dynamic + 'Component']); is like writing .TextComponent with nothing on the left side.
Now based on this, what are you trying to achieve exactly? Get the type or an instance of the type? What do you want to use the type for?
What you could do though would be to declare somewhere another global class and have these properties in them. Check this one for global variable declaration.
Your json could be something like this:
export class ComponentMapping
{
private TestComponent = TestComponent;
}
And then in your class access the test component accordingly.

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

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

Angular Compilation Error on import but method works

I have this external script which is added to the scripts sections of angular-cli.json
I then import it into my component and declare it as a variable.
Here is my component code
declare var radarChart: any;
import { Component, AfterViewInit, ElementRef } from '#angular/core';
import * as d3 from 'd3';
import '../../../libs/radarChart.js'
import './init-outcome-chart.js'
#Component({
selector: 'profile-component',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent {
constructor() {
RadarChart('', '', '');
}
}
The method inside the script I want to use is called RadarChart, so I call that in my constructor which works, however it gives me a syntax error saying its undefined. Doing radarChart.RadarChart get rids of the syntax error but on load of the web page, I get a console error marking radarChart (the variable) undefined.
What am I doing wrong

Categories

Resources