Angular 2 execute script after template render

后端 未结 4 1466
傲寒
傲寒 2021-01-31 13:32

So I have this slider component that use materializecss javascript. So after it\'s rendered, I need to execute

$(document).ready(function(){
    $(\'body\').on(\         


        
相关标签:
4条回答
  • 2021-01-31 14:11

    ngAfterViewInit() of AppComponent is a lifecycle callback Angular calls after the root component and it's children have been rendered and it should fit for your purpose.

    See also https://angular.io/guide/lifecycle-hooks

    0 讨论(0)
  • 2021-01-31 14:15

    Actually ngAfterViewInit() will initiate only once when the component initiate.

    If you really want a event triggers after the HTML element renter on the screen then you can use ngAfterViewChecked()

    0 讨论(0)
  • 2021-01-31 14:24

    I have found that the best place is in NgAfterViewChecked(). I tried to execute code that would scroll to an ng-accordion panel when the page was loaded. I tried putting the code in NgAfterViewInit() but it did not work there (NPE). The problem was that the element had not been rendered yet. There is a problem with putting it in NgAfterViewChecked(). NgAfterViewChecked() is called several times as the page is rendered. Some calls are made before the element is rendered. This means a check for null may be required to guard the code from NPE. I am using Angular 8.

    0 讨论(0)
  • 2021-01-31 14:26

    I've used this method (reported here )

    export class AppComponent {
    
      constructor() {
        if(document.getElementById("testScript"))
          document.getElementById("testScript").remove();
        var testScript = document.createElement("script");
        testScript.setAttribute("id", "testScript");
        testScript.setAttribute("src", "assets/js/test.js");
        document.body.appendChild(testScript);
      }
    }
    

    it worked for me since I wanted to execute a javascript file AFTER THE COMPONENT RENDERED.

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