考虑这个角6分量
@Component({
template: '<div my-directive>content</div>'
})
export class ACustomComponent {}
对于我来说,在指令的构造函数中插入组件的特定实例最简单的方法是什么?
@Directive()
export class MyDirective {
// how to reference the component whose template hosts this directive?
constructor(private hostComponent: Component) {}
}
我认为最简单的方法是使用
@Component()
,将组件实例存储在服务属性中,然后在指令中插入相同的服务并从该属性中检索实例。想知道是否有一种更简单、更通用的方法(所以我不必每次都提供该服务),这意味着该指令不需要知道其主机组件的类型。
我的问题是不同的
from this one
因为另一个需要直接应用指令的组件实例--
<my-cmp my-directive></my-cmp>
,我要的是最近的父组件,该指令是直接应用于它,还是应用于其模板中的本机HTML元素。
基本上,我要解决的问题是:我需要在指令中执行方法并将它们绑定到
this
在没有提前知道组件类型的指令的情况下承载它们的组件的上下文。
someMethod.bind(this.hostComponent)();