【问题标题】:custom event not getting fired in Angular自定义事件未在 Angular 中触发
【发布时间】:2018-02-19 07:04:37
【问题描述】:

我想查找列表中的元素是否在视口内。 为此,我想创建一个自定义事件并在其中调用一个方法。 活动无效。

以下是我尝试过的:

component.html

<div #myEl id="myEl_{{item.id}}" (inViewport)="onScreen($event,myEl)" *ngIf="!item.question" class="card panel m-b-" style="height:auto;">

inViewport 是我的自定义事件。

组件.ts

import { Component, OnInit, Input, AfterViewInit, OnDestroy, EventEmitter, Output} from '@angular/core';

@Component({
  selector: 'app-item',
  templateUrl: './item.component.html',
  styleUrls: ['./item.component.css']
})
export class ItemComponent implements OnInit, OnDestroy {
  @Output() inViewport: EventEmitter<any> = new EventEmitter();

 onScreen(event:any,selector) {

    var test = this.getElementOnScreen(selector);
    if (test)
      console.log(selector.id + " IS VISIBLE");
  }
}

现在这个 onScreen 没有被调用。 我可能错过了什么。

请指导!

谢谢

【问题讨论】:

    标签: angular events eventhandler


    【解决方案1】:

    你应该使用组件app-item的选择器

    <app-item #myEl id="myEl_{{item.id}}" (inViewport)="onScreen($event,myEl)" *ngIf="!item.question" class="card panel m-b-" style="height:auto;">
    

    【讨论】:

    • 我不能创建一个事件并在组件元素上使用它吗?
    • 您应该将其作为属性并将选择器作为属性选择器
    【解决方案2】:
        import { Component, Input, AfterViewInit, EventEmitter, Output} from '@angular/core';
    
        @Component({
          selector: 'app-item',
          template: '<div #myEl id="myEl_{{item.id}}" *ngIf="!item.question" class="card panel m-b-" style="height:auto;">
    ',
          styleUrls: ['./item.component.css']
        })
        export class ItemComponent implements AfterViewInit {
          @Output() inViewport: EventEmitter<any> = new EventEmitter();
    
          ngAfterViewInit() {
             console.log(selector.id + " IS VISIBLE");
             this.inViewport.emit(); 
          }
        }
    

    【讨论】:

      猜你喜欢
      • 2019-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多