Hi I have a script with name 'script.js' the problem is that I have a lot of functions there, and I need execute this function at the beginning of angular.
var appMaster = {
preLoader: function(){
},
smoothScroll: function() {
}
}
but I need to call this variable appMaster
import '../../assets/js/script.js';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
encapsulation: ViewEncapsulation.None
})
export class HomeComponent implements OnInit {
constructor() { }
ngOnInit() {
appMaster.preLoader();
appMaster.smoothScroll();
}
}
The error is appMaster no undeclared variable. How can I execute the functions within that other script?
Your need to export the appMaster variable from your script file if you want to use it elsewhere.
export let appMaster = { preLoader: function(){ }, smoothScroll: function() { } }; import {appMaster} from '../../assets/js/script.js'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'], encapsulation: ViewEncapsulation.None }) export class HomeComponent implements OnInit { constructor() { } ngOnInit() { appMaster.preLoader(); appMaster.smoothScroll(); } }
Hopefully you will like to use export/import statement.
If so then change you script.js and use export
var appMaster = {
preLoader: function(){},
smoothScroll: function() {}
}
export default appMaster;
In the component file use import
import anyName from "./path/to/file";
Call any function from script.js ,expample
anyName.preLoader()
Try like this :
Create javascript file named as common.js inside the following location in your project assets => js => script.js
common.js
var comman = (function() {
return {
masonryBuild: function() {
console.log('preLoader');
}
}
})(comman || {})
open .angular-cli.json file then add external javascript file path like below
"scripts": [
"../src/assets/js/comman.js"
]
declare script var name in your typescript like :
component.ts
declare var comman: any;
export class Component {
ngOnInit() {
comman.masonryBuild();
}
}
You can call varibale from anthoer script in Angular application.
Step 1. Create demo.js file in assests/javascript folder.
export function test1(){
console.log('Calling test 1 function');
}
Step 2. Create demo.d.ts file in assests/javascript folder.
export declare function test1();
Step 3. Use it in your component
//User defined file path
import { test1 } from '../assets/javascript/demo';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor() {
console.log(test1());
}
}
Note: js and .d.ts file name shoule be same
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.