这是我的代码指令:
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/