Angular2如何仅在存在父组件的情况下将其注入指令中? [英] Angular2 how to inject parent component into directive only if it's there?

查看:44
本文介绍了Angular2如何仅在存在父组件的情况下将其注入指令中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的自定义表格组件具有全选指令.我希望我的指令的用户能够以两种方式实例化它:

I have a select-all directive for my custom table component. I'd like a user of my directive to be able to instantiate it in two ways:

1:

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

2:

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

我能够通过在指令的构造函数中使用Host,Inject和forwardRef获得第一种方法:

I was able to get the first way working through the use of Host, Inject, and forwardRef in my directive's constructor:

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

但是当我用第二种方法实例化它时,我收到一个异常,抱怨没有MyCustomTableComponent的提供者,大概是因为MyCustomTableComponent不是第二种实例化方法的父对象,因此Host和forwardRef不返回任何内容...

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(如果存在),否则使用传递给它的任何表作为输入...

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...

推荐答案

您可以使用@Optional()装饰器将依赖项设置为可选:

You can make a dependency optional using the @Optional() decorator:

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

这篇关于Angular2如何仅在存在父组件的情况下将其注入指令中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆