【问题标题】:How I do an "onload" event in Angular 5?我如何在 Angular 5 中执行“onload”事件?
【发布时间】:2018-10-23 02:17:35
【问题描述】:

我正在尝试调用函数 onload 元素,例如 Javascript 中的 onload="function()"。

所以这是代码:

<div class="img-circle" [id]="pet.id" (load)="imgLoad( pet.id, pic )"></div>

功能工作正常,我尝试使用 (click) 并且可以工作,但我尝试使用 (load)、(onload)、(loaded) 并且不工作。

【问题讨论】:

  • 为什么不使用 constructorngOnInit 进行加载?
  • 你想 autofocus 在 div 上吗?
  • 但是这个 div 在 ngFor 内部,params 的 de 值在 ngFor 加载值时获取值
  • 没有自动对焦,只加载div

标签: javascript angular events dom-events event-binding


【解决方案1】:

替换 onload 函数的正确方法是使用ngOnInit。只需在应用组件上实现OnInit

更多信息:https://angular.io/api/core/OnInit

【讨论】:

  • 我认为这不包括动态内容,例如*ngIf条件
【解决方案2】:

试试 HostListener。

@HostListener('document:click', ['$event'])
runThisMethod() {
  // your code goes here.
}

当鼠标点击文档时,运行此方法。 但是对于自定义 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');
        }
    }

【讨论】:

  • 我用下面的答案解决了我的问题,但感谢您的帮助。
【解决方案3】:

在我的函数中,我尝试在此 div 中应用样式,参数是设置背景图像:url(base64);

所以...我改成这个,并且可以工作

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

事件绑定(加载、加载、加载)不存在。

【讨论】:

  • 很高兴知道你解决了你的问题,但 ngStyle 是不同的东西。更适合使用的是 ngAfterViewInt()
猜你喜欢
  • 2015-03-31
  • 1970-01-01
  • 2011-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-01
相关资源
最近更新 更多