angular - 从 Angular 2 中的指令调用组件的方法

标签 angular

这是我的代码指令:

import { Directive, HostListener, ElementRef } from '@angular/core';

@Directive({
  selector: '[appScrollToEnd]'
}) 
export class ScrollToEndDirective {
  constructor(private element: ElementRef) { }
  @HostListener('scroll') onScroll(){
    console.log(this.element
  } 
}

在我的 View 模板中

<div class="content" appScrollToEnd="functionInComponent($event)"></div>

如何调用方法 functionInComponent()滚动时。我知道 angular2 可以监听事件滚动,但我的目的是从指令中调用组件的方法。谢谢

最佳答案

你可以在你的指令中有一个@Output 事件,并在你使用它的任何地方将它绑定(bind)到某个组件方法,

@Directive({
  selector: '[appScrollToEnd]'
}) 
export class ScrollToEndDirective {
  @Output() appScrollToEnd = new EventEmitter();

  constructor(private element: ElementRef) { }

  @HostListener('scroll') onScroll(){
    this.appScrollToEnd.emit('someValue');
  } 
}


@Component({
  selector: 'my-app',
  template: `
    <div class="content" (appScrollToEnd)="functionInComponent($event)">
      <div class="text">Some text</div> 
    </div>
  `,
})
export class App {
  functionInComponent(e) {
    console.log(e):
  }
}

感谢 @yurzui 提供 Plunker 示例。

这里是 Plunker!!

关于angular - 从 Angular 2 中的指令调用组件的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46527290/

相关文章:

angular - 使用 Webpack 5 模块联合提供样式和 Assets

Angular 2。如何在标签 "URL"中使用 *ngFor 设置 "href"并在条件 *ngIf 中设置 '{{theme.name}}'?

html - 如何增加 Angular Material 中 mat-select 表单的宽度?

c# - 将图像/文件从 Angular 7 上传到 .net core

angular - 如何在 Angular 2 中为异步验证器添加去抖动时间?

angular - 如何将 HTML 的属性输入到 typescript 中

typescript - 未定义的组件没有路由配置,也就是如何配置 Angular 2 路由器进行单元测试?

angular - 如何将 Subjects 和 Observables 与 Angular rxjs 结合起来

angular - 一个应用程序中的多个 ngrx 存储

angular - 使用 Angular2/AngularFire2 创建或增加一个值