Security
Angular seems to be pulling script tags from HTML templates.
From Angular Docs :
It removes the <script > tag, but retains safe content, such as the text content of the <script>
Angular provides workaround methods, but for your use, this seems like a useful service.
Services
The preferred way to include your own script in your component from a separate dedicated file is to create.
I took the code from your Plunker 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 user code as follows:
// 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(); } }
Life cycle interceptions
If you want to call your special service code at some point, you can use lifecycle bindings . For example, you can call your code using ngAfterViewInit() instead of ngOnInit() if you want to wait for the view to load.
source share