在组件树上获取对特定类型的所有指令的引用

Avi*_* P. 4 angular

我有一个复杂的场景,我需要帮助.

我有一个指令(称为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,b,a -->
            </div>
          </div>
        </div>
        <div appQuery>
          <!-- In here I want to have a reference to TagDirectives instances
              f,e,b,a -->
        </div>
      </div>
    </div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我知道我可以TagDirective通过让注入器在构造函数中提供它来单独获取对host元素的引用QueryDirective,我也知道我可以通过注入ViewContainerRef并使用其parentInjector成员来请求类型的实例来获得下一个更高的实例TagDirective.

但是,我还没有找到进一步推进树的方法,并将所有实例一直收集到根目录.

我怎么做到这一点?谢谢!

yur*_*zui 8

由于每个元素都有自己的注入器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);
  }
}
Run Code Online (Sandbox Code Playgroud)

Stackblitz示例

在上面的代码中,我提供TAG_DIRECTIVES_TOKEN了每个div[appTag]元素.我使用具有以下依赖项的工厂:

deps: [TagDirective, [ new SkipSelf(), new Optional(), TAG_DIRECTIVES_TOKEN ]]
           ^^^^^                                            ^^^^^
current instance of TagDirective        parent optional TAG_DIRECTIVES_TOKEN  
Run Code Online (Sandbox Code Playgroud)

哪里:

  • SkipSelf 告诉角度编译器跳过当前令牌并使用我们在父节点中提供的令牌 div[appTag]

  • Optional这里使用的是因为根div[appTag]元素无法识别父元素,TAG_DIRECTIVES_TOKEN因此角度编译器不会引发错误:

没有提供的InjectionToken标签指令!