如何在组件渲染后从指令中调用函数?
问题描述:
如何在组件渲染后从指令调用函数?如何在组件渲染后从指令中调用函数?
我有分量:
export class Component {
ngAfterContentInit() {
// How can i call functionFromDirective()?
}
}
而且我想调用这个函数:
export class Directive {
functionFromDirective() {
//something hapenns
}
我怎样才能做到这一点?
答
您可以从组件模板与ViewChild
这样的检索指令:
@Directive({
...,
selector: '[directive]',
})
export class DirectiveClass {
method() {}
}
在您的组件:
import { Component, ViewChild } from '@angular/core'
import { DirectiveClass } from './path-to-directive'
@Component({
...,
template: '<node directive></node>'
})
export class ComponentClass {
@ViewChild(DirectiveClass) directive = null
ngAfterContentInit() {
// How can i call functionFromDirective()?
this.directive.method()
}
}
答
从一个组件内调用的方法是不是一个好主意。使用指令有助于模块化设计,但是当您调用该方法时,会从组件中获取对指令的依赖关系。
相反,该指令应实现AfterViewInit接口:
@Directive({
...,
selector: '[directive]',
})
export class DirectiveClass implements AfterViewInit {
ngAfterViewInit(): void {}
}
这样一来,你的组件不必知道该指令什么。
非常感谢!你真的帮助我。 –