最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How I do an "onload" event in Angular 5? - Stack Overflow

programmeradmin8浏览0评论

I am trying to call a function onload element, like a onload="function()" in Javascript.

So this is the 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.

I am trying to call a function onload element, like a onload="function()" in Javascript.

So this is the 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.

Share Improve this question edited Dec 24, 2020 at 0:17 peterh 1 asked May 13, 2018 at 5:34 Guilherme de MelloGuilherme de Mello 811 gold badge2 silver badges6 bronze badges 4
  • 2 Why dont use it constructor or ngOnInit for load ? – Mohammad Daliri Commented May 13, 2018 at 5:45
  • Do you want autofocus on div? – Mohammad Daliri Commented May 13, 2018 at 6:00
  • But the this div is inside a ngFor and de values of params get the value when the ngFor load values – Guilherme de Mello Commented May 13, 2018 at 6:00
  • Without autofocus, just div load – Guilherme de Mello Commented May 13, 2018 at 6:04
Add a ment  | 

3 Answers 3

Reset to default 6

The proper way of replacing the onload function is by using ngOnInit. Just implement OnInit on the app ponent.

More info: https://angular.io/api/core/OnInit

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:

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

In my function i trying to aplication a style in this div, the params was to set a background-image: url(base64);

So... I change to this, and works

[ngStyle]="{ 'background-image': 'url(' + pic + ') '}

Event-binding (load,onload,loaded) doesn't exists.

发布评论

评论列表(0)

  1. 暂无评论