[jquery] Angular 2 execute script after template render

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

$(document).ready(function(){
    $('body').on('Slider-Loaded',function(){
        console.log('EVENT SLIDER LOADED');
        $('.slider').slider({full_width: true});
        $('.slider').hover(function () {
            $(this).slider('pause');
        }, function () {
            $(this).slider('start')
        });
    });
});

But I don't quite knows where to put this line since typescript/angular remove script tag in templates. I've included JQuery in the ts files and was hoping to use the event system, but that doesn't seems to work. Any ideas? Here's the code of the ts file:

/// <reference path="../../typings/main.d.ts" />
import {Component, Input} from 'angular2/core';
import { RouterLink } from 'angular2/router';
import {ServerService} from './server';


@Component({
    selector: 'slider',
    templateUrl:'/app/template/slider.html',
    directives: [  ],
})

export class SliderComponent {
    @Input() images;
    private server: ServerService;
    public constructor(server: ServerService){
        this.server = server;
    }

    ngOnInit() {
        console.log("THROWING EVENT");
        $('body').trigger('Slider-Loaded');
    }
}

This question is related to jquery angular typescript

The answer is


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


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


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.


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.


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?