如何从组件html加载脚本文件? [英] How to load script file from component html?
问题描述
基本上我想加载组件html特定的脚本文件,所以脚本
我要把脚本
在组件html本身内部的文件引用,我看到在页面上呈现组件html时忽略了内部脚本
文件。
Basically I wanted to load component html specific script file, so that script
I'm going to put script
file reference inside component html itself, I'm seeing that inner script
file has been ignored while rendering component html on page.
组件
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: 'test.html'
})
export class AppComponent { }
test.html
<div>
<h1>My First Angular 2 App</h1>
</div>
<script src="test.js"></script>
以上是我的代码我试过的&我已经有 test.js
了。
Above is my code what I tried & I already have test.js
there in place.
有没有办法加载组件特定的javascript文件与组件OR它的HTML?
Is there any way to load component specific javascript file with component OR with its html?
推荐答案
工作偷窃者
安全性
看起来Angular从Html模板中取出脚本标签。
Working Plunker
Security
It looks like Angular takes out script tags from Html templates.
来自 Angular文档:
它删除了
< script
>标签但是保持安全内容,例如< script>
标签的文本内容
It removes the
<script
> tag but keeps safe content, such as the text content of the<script>
tag
Angular提供绕过的方法安全,但对于您的用例,它看起来像服务会有所帮助。
Angular provides methods to bypass security, but for your use case it looks like a service would be helpful.
从单独的组件中将自己的自定义脚本包含在组件中的首选方法专用文件将创建服务。
The preferred way to include your own custom script in your component from a separate dedicated file would be to create a service.
我从您的Plunker的script.js文件中获取代码并将其放入如下服务中:
I took the code from your Plunker's script.js file and put it into a service like this:
// File: app/test.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class TestService {
testFunction() {
console.log('Test');
}
}
然后我导入了服务并调用了自定义代码这个:
Then I imported the service and called the custom code like this:
// File: app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { TestService } from './test.service';
@Component({
selector: 'my-app',
templateUrl: 'test.html',
providers: [TestService]
})
export class AppComponent implements OnInit {
constructor(private testService: TestService) {}
ngOnInit() {
this.testService.testFunction();
}
}
生命周期挂钩
如果您想在特定点调用服务的自定义代码,您可以利用生命周期钩子。例如,您可以使用 ngAfterViewInit()
而不是 ngOnInit()
来调用您的代码,如果您想等到视图已加载。
Lifecycle hooks
If you want to call your service's custom code at a specific point you can take advantage of lifecycle hooks. For example you can call your code using the ngAfterViewInit()
instead of ngOnInit()
if you want to wait until the view has loaded.
这篇关于如何从组件html加载脚本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!