How to load script file from html component?

Basically, I wanted to load the html component script component file, so the script I am going to put a link to the script file inside the html component itself, I see that the internal script file was ignored while rendering the html component on the page.

Component

 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> 

Above is my code that I tried, and I already have test.js there.

Plunkr here

Is there a way to load a component javascript file with an OR component from its html?

+5
source share
1 answer

Working plunker

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.

+9
source

All Articles