简体   繁体   English

Angular2如何将父组件注入指令只有它在那里?

[英]Angular2 how to inject parent component into directive only if it's there?

I have a select-all directive for my custom table component. 我的自定义表组件有一个select-all指令。 I'd like a user of my directive to be able to instantiate it in two ways: 我希望我的指令的用户能够以两种方式实例化它:

1: 1:

<my-custom-table>
    <input type="checkbox" my-select-all-directive/>
</my-custom-table>

2: 2:

<input type="checkbox" [table]="myTableRef" my-select-all-directive/>
<my-custom-table #myTableRef></my-custom-table>

I was able to get the first way working through the use of Host, Inject, and forwardRef in my directive's constructor: 我能够通过在我的指令构造函数中使用Host,Inject和forwardRef来获得第一种方法:

constructor(@Host() @Inject(forwardRef(() => MyCustomTableComponent)) table?: MyCustomTableComponent) {
    this.table = table; //later I can call this.table.selectAll();
}

But when I instantiate it the second way, I get an exception that complains that there is no provider for MyCustomTableComponent, presumably because MyCustomTableComponent isn't the parent in the second way of instantiation, so Host and forwardRef return nothing... 但是当我以第二种方式实例化它时,我得到一个异常,抱怨没有MyCustomTableComponent的提供者,大概是因为MyCustomTableComponent不是第二种实例化方式的父级,所以Host和forwardRef什么都不返回...

How can I make that parameter optional? 如何使该参数可选? So my directive uses its parent or grandparent MyCustomTableComponent if it exists, or otherwise uses whatever table is passed to it as input... 所以我的指令使用其父或祖父母MyCustomTableComponent(如果存在),或者使用传递给它的任何表作为输入...

You can make a dependency optional using the @Optional() decorator: 您可以使用@Optional()装饰@Optional()依赖项可选:

constructor(@Optional() @Host() @Inject(forwardRef(() => MyCustomTableComponent)) table?: MyCustomTableComponent) {
    this.table = table; //later I can call this.table.selectAll();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular2,如何将事件从父组件广播到子指令? - Angular2,How to broadcast event from parent component to child directive? Angular2:通过指令将外部Component注入其他组件无效 - Angular2: Inject external Component into other component via directive not working Angular2组件如何导入指令组件? - Angular2 Component How to Import Directive Component? angular2中没有提供服务错误的提供程序,为什么我需要将其注入到其父组件中? - No provider for service error in angular2, why do I need to inject it in it's parent component? 在 Angular 中,有没有办法将包含组件指令的 html 注入到父组件的模板中? - In Angular is there a way to inject html that contains a component directive into the template of a parent component? 如何在angular2中注入组件实例 - How to inject a component instance in angular2 如何使用Angular2将服务注入动态组件 - How to inject a service into a dynamic component with Angular2 如何将组件注入angular2中的div选择器 - How to inject component into a div selector in angular2 如何访问 Angular2 指令上的组件? - How to access the Component on a Angular2 Directive? 在Angular2中使用父组件的模板 - Using parent component's template in Angular2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM