模板渲染后Angular 2执行脚本 [英] Angular 2 execute script after template render

查看:85
本文介绍了模板渲染后Angular 2执行脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个使用materializecss javascript的滑块组件.所以在渲染之后,我需要执行

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

但是我不太知道在哪里放置这行,因为typescript/angular删除了模板中的script标签.我已经在ts文件中包含了JQuery,并希望使用事件系统,但这似乎不起作用.有任何想法吗?这是ts文件的代码:

/// <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');
    }
}

AppComponent

解决方案

ngAfterViewInit()是生命周期回调Angular在根组件及其子组件被渲染之后调用,并且应该适合您的目的.

另请参见 https://angular.io/guide/lifecycle-hooks

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

解决方案

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

这篇关于模板渲染后Angular 2执行脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆