javascript 我如何在 Angular 5 中执行“onload”事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50313068/
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
How i do a "onload" event in Angular 5
提问by Guilherme de Mello
I'm trying to call a function onload element, like a onload="function()" in Javascript.
我正在尝试调用函数 onload 元素,例如 Javascript 中的 onload="function()" 。
So this is code
所以这是代码
<div class="img-circle" [id]="pet.id" (load)="imgLoad( pet.id, pic )"></div>
Function is working fine, I try with (click) and works, but I try with (load), (onload), (loaded) and not working.
功能工作正常,我尝试使用 (click) 并工作,但我尝试使用 (load)、(onload)、(loaded) 并且不工作。
采纳答案by Guilherme de Mello
In my function i trying to aplication a style in this div, the params was to set a background-image: url(base64);
在我的函数中,我试图在这个 div 中应用一个样式,参数是设置一个背景图像: url(base64);
So... I change to this, and works
所以......我改变了这个,并且有效
[ngStyle]="{ 'background-image': 'url(' + pic + ') '}
Event-binding (load,onload,loaded) doesn't exists.
事件绑定 (load,onload,loaded) 不存在。
回答by Shadab Faiz
Try HostListener.
试试主机监听器。
@HostListener('document:click', ['$event'])
runThisMethod() {
// your code goes here.
}
When mouse is clicked on document, then run this method. However for custom div, use directives + HostListener. For Ex:
当鼠标单击文档时,然后运行此方法。但是对于自定义 div,请使用指令 + HostListener。例如:
<app-myComponent appChbgcolor> {{title}} </app-myComponent>
@Directive({
selector: '[appChbgcolor]'
})
export class ChangeBgColorDirective {
constructor(private el: ElementRef, private renderer: Renderer) {
this.ChangeBgColor('red');
}
ChangeBgColor(color: string) {
this.renderer.setElementStyle(this.el.nativeElement, 'color', color);
}
@HostListener('onload') onClick() {
window.alert('Host Element Clicked');
}
}
回答by Hola Soy Edu Feliz Navidad
The proper way of replacing the onload function is by using ngOnInit. Just implement OnIniton the app component.
替换 onload 函数的正确方法是使用ngOnInit. 只需OnInit在应用程序组件上实现即可。
More info: https://angular.io/api/core/OnInit

