我有一个复杂的场景,我需要帮助.
我有一个指令(称为TagDirective),它放在我的应用程序的多个元素上.我有另一个指令(QueryDirective),它需要引用其主机元素上存在的TagDirective的所有实例,以及层次结构中它上面的所有元素.
例:
<div appTag="a"> <div appTag="b"> <div appTag="c"> <div appTag="d"> <div appQuery> <!-- In here I want to have a reference to TagDirectives instances d,c,b,a --> </div> </div> </div> <div appTag="e"> <div appTag="f"> <div appTag="g"> <div appTag="h"> <div appQuery> <!-- In here I want to have a reference to TagDirectives instances h,g,f,e,a --> </div> </div> </div> <div appQuery> <!-- In here I want to have a reference to TagDirectives instances f,a --> </div> </div> </div> </div> </div>
我知道我可以通过让注入器在QueryDirective的构造函数中提供它来单独获取对host元素的TagDirective的引用,我也知道我可以通过注入ViewContainerRef并使用其parentInjector成员来请求实例来获取下一个更高的实例键入TagDirective.
但是,我还没有找到进一步推进树的方法,并将所有实例一直收集到根目录.
我怎么做到这一点?谢谢!
解决方法
由于每个元素都有自己的注入器,我们不能只使用multi:true它只有在我们在同一个元素上提供相同的标记时才有效.
可能的解决方法如下:
export const TAG_DIRECTIVES_TOKEN = new InjectionToken('tags directives'); export function tagDirectiveFactory(dir: TagDirective,token: TagDirective[]) { return token ? [dir,...token] : [dir]; } @Directive({ selector: '[appTag]',providers: [{ provide: TAG_DIRECTIVES_TOKEN,useFactory: tagDirectiveFactory,deps: [TagDirective,[ new SkipSelf(),new Optional(),TAG_DIRECTIVES_TOKEN ]] }] }) export class TagDirective {} @Directive({ selector: '[appQuery]' }) export class AppQueryDirective { constructor(@Inject(TAG_DIRECTIVES_TOKEN) private directives: TagDirective[]){ console.log(directives); } }
在上面的代码中,我在每个div [appTag]元素上提供TAG_DIRECTIVES_TOKEN.我使用具有以下依赖项的工厂:
deps: [TagDirective,TAG_DIRECTIVES_TOKEN ]] ^^^^^ ^^^^^ current instance of TagDirective parent optional TAG_DIRECTIVES_TOKEN
哪里:
> SkipSelf告诉角度编译器跳过当前令牌并使用我们在父div [appTag]中提供的令牌
>这里使用了可选,因为root div [appTag]元素无法识别父TAG_DIRECTIVES_TOKEN,因此角度编译器不会引发错误:
No provider for InjectionToken tags directives!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。