Angular: 从另一指令获取主机上一个指令实例的引用
Angular: Get reference of one directive instance on host from another directive
我的模板:
<div myDirective myOtherDirective>Hello World</div>
我的指令:
@Directive({
selector: '[myDirective]',
})
export class MyDirective {
private readonly otherDirective: MyOtherDirective; // How to instantiate this?
}
如何从 MyDirective
中获取对 myOtherDirective
的引用?
应该可以通过 DI 获得
@Directive({
selector: '[myDirective]',
})
export class MyDirective {
constructor(private otherDirective: MyOtherDirective) {}
}
如果在同一元素上没有这样的指令,那么请确保使用 @Optional
装饰器。
或者,您可以将其作为 @Input
我的-other.directive.ts
@Directive({
selector: '[myOtherDirective]',
exportAs: 'myOtherDirective'
})
export class MyOtherDirective {}
template.html
<div myDirective [otherDirective]="other" #other="myOtherDirective"
myOtherDirective>Hello World</div>
my.directive.ts
@Directive({
selector: '[myDirective]',
})
export class MyDirective {
@Input() otherDirective: MyOtherDirective;
}
我的模板:
<div myDirective myOtherDirective>Hello World</div>
我的指令:
@Directive({
selector: '[myDirective]',
})
export class MyDirective {
private readonly otherDirective: MyOtherDirective; // How to instantiate this?
}
如何从 MyDirective
中获取对 myOtherDirective
的引用?
应该可以通过 DI 获得
@Directive({
selector: '[myDirective]',
})
export class MyDirective {
constructor(private otherDirective: MyOtherDirective) {}
}
如果在同一元素上没有这样的指令,那么请确保使用 @Optional
装饰器。
或者,您可以将其作为 @Input
我的-other.directive.ts
@Directive({
selector: '[myOtherDirective]',
exportAs: 'myOtherDirective'
})
export class MyOtherDirective {}
template.html
<div myDirective [otherDirective]="other" #other="myOtherDirective"
myOtherDirective>Hello World</div>
my.directive.ts
@Directive({
selector: '[myDirective]',
})
export class MyDirective {
@Input() otherDirective: MyOtherDirective;
}