Reputation: 14280
I make a site with Angular 2 and will add a JavaScript file to the component. This script must render the height of some images equal to the height of the window of the browser.
How could I add this script to the component?
The solutions I found on SO or anywhere else, looks like this:
import './home.component.js';
But it's not what I need! I need this in my home.component.ts
file:
@Component({
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss'],
jsUrls: ['./home.component.js']
})
or something...
Update 1: In my site I use Angular CLI and TypeScript.
Update 2: You could find my project on GitHub: https://github.com/WatchFriends/Web
Upvotes: 1
Views: 1712
Reputation: 4888
This works, and works well:
In the angular-cli.json file, there is a section, "scripts". Add the path to your script in that array (as a double-quoted string).
Here's a frag from that file:
"mobile": false,
"styles": [
"../node_modules/bootstrap/dist/css/bootstrap.css",
"../node_modules/font-awesome/css/font-awesome.css",
"styles.css"
],
"scripts": ["./app/my_script.js"],
"environments": {
"source": "environments/environment.ts",
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
my_script is this:
function sayHello ( ) {
console.log ( 'I am saying hello' );
}
Then just call it like you'd expect from anywhere. To beat the annoying "not found" error you may get in your IDE, you can either just do this:
window [ 'sayHello' ] ( );
Or create a utility class that contains a reference to that function, such that you can import the class and call the function as usual (you are basically just providing a framework facade for your "my_script.js" functions).
I tried both, it worked just fine, no errors (you are using ng serve or ng build of course etc).
Upvotes: 3