Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
    }
}
like image 285
Carl Boisvert Avatar asked Mar 23 '16 17:03

Carl Boisvert


2 Answers

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

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

like image 198
Günter Zöchbauer Avatar answered Oct 27 '22 20:10

Günter Zöchbauer


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

like image 13
Coltin Casmir Avatar answered Oct 27 '22 19:10

Coltin Casmir