jQuery Angular 2 在模板渲染后执行脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36184458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 2 execute script after template render
提问by Carl Boisvert
So I have this slider component that use materializecss javascript. So after it's rendered, I need to execute
所以我有这个使用 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')
});
});
});
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:
但我不太知道把这一行放在哪里,因为打字稿/角度删除了模板中的脚本标签。我在 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');
}
}
回答by Günter Z?chbauer
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.
ngAfterViewInit()
ofAppComponent
是一个生命周期回调,Angular 在根组件及其子组件被渲染后调用,它应该适合您的目的。
回答by Coltin Casmir
Actually ngAfterViewInit()
will initiate only once when the component initiate.
实际上ngAfterViewInit()
只会在组件启动时启动一次。
If you really want a event triggers after the HTML element renter on the screen then you can use ngAfterViewChecked()
如果您真的希望在屏幕上的 HTML 元素租用者之后触发事件,那么您可以使用 ngAfterViewChecked()
回答by Cauêh Q.
I've used this method (reported here)
我用过这种方法(报告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.
它对我有用,因为我想在组件渲染后执行一个 javascript 文件。