如何从组件html加载脚本文件?

时间:2016-07-02 19:02:20

标签: javascript angular

基本上我想加载组件html特定的脚本文件,以便script我将script文件引用放在组件html本身中,我看到内部script在页面上渲染组件html时,文件已被忽略。

组件

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>

以上是我的代码,我尝试过的&amp;我已经有test.js了。

Plunkr Here

有没有办法用组件OR加载组件特定的javascript文件及其html?

1 个答案:

答案 0 :(得分:10)

Working Plunker

安全

看起来Angular从Html模板中取出脚本标签。

来自Angular Docs

  

删除<script&gt;标记但保留安全内容,例如<script>标记

的文本内容

Angular为bypass security提供方法,但对于您的用例,它看起来像服务会有所帮助。

服务

从单独的专用文件中将自己的自定义脚本包含在组件中的首选方法是创建service

我从您的Plunker的script.js文件中获取了代码并将其放入如下服务中:

// File: app/test.service.ts
import { Injectable } from '@angular/core';

@Injectable()
export class TestService {
    testFunction() {
      console.log('Test');
    }
}

然后我导入了服务并调用了这样的自定义代码:

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

生命周期挂钩

如果您想在特定时刻拨打服务的自定义代码,可以利用lifecycle hooks。例如,如果您想要等到视图加载,则可以使用ngAfterViewInit()而不是ngOnInit()来调用代码。

相关问题