How to load script file from component html?

后端 未结 1 2050
独厮守ぢ
独厮守ぢ 2020-12-06 03:33

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

相关标签:
1条回答
  • 2020-12-06 03:50

    Working Plunker

    Security

    It looks like Angular takes out script tags from Html templates.

    From the Angular Docs:

    It removes the <script> tag but keeps safe content, such as the text content of the <script> tag

    Angular provides methods to bypass security, but for your use case it looks like a service would be helpful.

    Services

    The preferred way to include your own custom script in your component from a separate dedicated file would be to create a service.

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

    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.

    0 讨论(0)
提交回复
热议问题