gpt4 book ai didi

Angular:从另一个指令获取主机上一个指令实例的引用

转载 作者:行者123 更新时间:2023-12-04 00:25:34 26 4
gpt4 key购买 nike

我的模板:

<div myDirective myOtherDirective>Hello World</div>

我的指令:
@Directive({
selector: '[myDirective]',
})
export class MyDirective {
private readonly otherDirective: MyOtherDirective; // How to instantiate this?
}

我如何获得对 myOtherDirective 的引用从内部 MyDirective ?

最佳答案

它应该可以通过 DI 获得

@Directive({
selector: '[myDirective]',
})
export class MyDirective {
constructor(private otherDirective: MyOtherDirective) {}
}

如果同一个元素上没有这样的指令,那么请确保您使用 @Optional装饰者。

或者,您可以将其作为 @Input 传递

my-other.directive.ts
@Directive({
selector: '[myOtherDirective]',
exportAs: 'myOtherDirective'
})
export class MyOtherDirective {}

模板.html
<div myDirective [otherDirective]="other" #other="myOtherDirective" 
myOtherDirective>Hello World</div>

my.directive.ts
@Directive({
selector: '[myDirective]',
})
export class MyDirective {
@Input() otherDirective: MyOtherDirective;
}

关于Angular:从另一个指令获取主机上一个指令实例的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57247686/

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