admin管理员组文章数量:1323330
Let's just say I make a custom JavaScript file ie 'custom.js'
How would I implement this into a Component?
If I add 'custom.js' to index.html, that's fine but is there any way I can add it specifically to the ponent?
Let's just say I make a custom JavaScript file ie 'custom.js'
How would I implement this into a Component?
If I add 'custom.js' to index.html, that's fine but is there any way I can add it specifically to the ponent?
Share edited Dec 1, 2017 at 19:04 Brian 5,0593 gold badges22 silver badges30 bronze badges asked Dec 1, 2017 at 18:58 Eddie Taliaferro IIEddie Taliaferro II 1851 gold badge5 silver badges16 bronze badges 4- what would this file have? – yBrodsky Commented Dec 1, 2017 at 18:59
- animation, ect. For example, moving around a navigation bar, ect – Eddie Taliaferro II Commented Dec 1, 2017 at 19:00
-
Can't you just
import
from inside your ponent definition? Although, I guess that would require it to be a module. Is it possible to change your custom.js into a module? – mhodges Commented Dec 1, 2017 at 19:08 - Can you show how your .js looks like and where you have kept it in your project? – Manzer A Commented Dec 1, 2017 at 19:44
3 Answers
Reset to default 6Step: 1=> Create and write your js code say "synapse.js" in /app folder. The function or constant which you to use in a ponent should be exported using export
keyword. for ex:
synapse.js
export function synapseThrow() {
return 'hello'
}
export const MY_VAR = 'world!';
Step: 2=> in angular-cli.json, add the below part in apps
object.
"scripts": ["app/synapse.js"]
Step: 3=> in tsconfig.json, add the below property in pilerOptions
.
"allowJs": true
Step: 4=> in any ponent say in "app.ponent.ts" import the "synapse.js" file using import
keyword.
app.ponent.ts
// other imports
import { MY_VAR, synapseThrow } from './synapse';
// other app code here
ngOnInit(){
const returned = MY_VAR;
const returnFunc = synapseThrow();
}
Try this way:
- Put js file in path: assets/js/custom.js
- Code your ponent
ts file
export class MyComponent implements AfterViewChecked {
constructor(private elementRef: ElementRef) {
}
ngAfterViewChecked() {
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "../assets/js/custom.js";
this.elementRef.nativeElement.appendChild(s);
}
}
Try declaring a variable that you have inside of your custom.js file
declare var aFunction: any;
import '../../../js/custom.js';
export class ExampleComponent{
variable: any;
constructor() { }
ngOnInit() {
new aFunction(this.variable); //aFunction() is inside custom.js
}
}
本文标签: Adding JavaScript File to Angular 4 ComponentStack Overflow
版权声明:本文标题:Adding JavaScript File to Angular 4 Component - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742139535a2422520.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论