gpt4 book ai didi

Angular 6 指令 : get reference to the host component instance

转载 作者:行者123 更新时间:2023-12-04 13:02:42 27 4
gpt4 key购买 nike

考虑这个 Angular 6 组件

@Component({
template: '<div my-directive>content</div>'
})
export class ACustomComponent {}

我在指令的构造函数中注入(inject)组件的特定实例的最简单方法是什么?
@Directive()
export class MyDirective {
// how to reference the component whose template hosts this directive?
constructor(private hostComponent: Component) {}
}

我想到的最简单的方法是使用 @Component() 中提供的服务。 ,将组件实例存储在服务属性中,然后在指令中注入(inject)相同的服务并从该属性中检索实例。想知道是否有一种更简单、更通用的方法(所以我不必每次需要都提供该服务),这意味着指令不需要知道其主机组件的类型。

PS:我的问题不一样 from this one因为另一个想要指令直接应用于的组件实例-- <my-cmp my-directive></my-cmp> ,我要询问最近的父组件,该指令是直接应用于它还是应用于其模板中的 native HTML 元素。

基本上,我要解决的问题是:我需要在指令中执行方法并将它们绑定(bind)到 this托管它们的组件的上下文,而指令不提前知道组件的类型。
someMethod.bind(this.hostComponent)();

最佳答案

对于动态组件类型,我喜欢这个,它适用于 Angular 9。

export class FromItemComponentBase  {
constructor(private hostElement: ElementRef) {
hostElement.nativeElement.__component=this;
}
}
@Component({
selector: 'input-error',
templateUrl: 'component.html'
})
export class FromItemErrorComponent extends FromItemComponentBase {
constructor(private hostElement: ElementRef) {
super(hostElement);
}
}

@Component({
selector: 'input-password',
templateUrl: 'component.html'
})
export class FromItemPasswordComponent extends FromItemComponentBase {
constructor(private hostElement: ElementRef) {
super(hostElement);
}
}
@Directive({selector: 'input-error,input-password,input-text'})
export class FormInputDirective {
component:FromItemComponentBase;

constructor(private hostElement: ElementRef) {
this.component=hostElement.nativeElement.__component;
}
}

关于 Angular 6 指令 : get reference to the host component instance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51718399/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com