加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 获取组件树上某种类型的所有指令的引用

发布时间:2020-12-17 17:33:54 所属栏目:安全 来源:网络整理
导读:我有一个复杂的场景,我需要帮助. 我有一个指令(称为TagDirective),它放在我的应用程序的多个元素上.我有另一个指令(QueryDirective),它需要引用其主机元素上存在的TagDirective的所有实例,以及层次结构中它上面的所有元素. 例: div appTag="a" div appTag="
我有一个复杂的场景,我需要帮助.

我有一个指令(称为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);
  }
}

Stackblitz Example

在上面的代码中,我在每个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!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读