![](/img/trans.png)
[英]How to call a Directive/Component's function inside rendered Angular 2
[英]How can I call function from directive after component's rendering?
如何在组件渲染后从指令调用函数?
我有组件:
export class Component {
ngAfterContentInit() {
// How can i call functionFromDirective()?
}
}
我想要调用这个函数:
export class Directive {
functionFromDirective() {
//something hapenns
}
我怎样才能做到这一点?
您可以使用ViewChild
从Component的模板中检索Directive,如下所示:
@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 {}
}
这样,您的组件就不必了解该指令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.