如何并且是!在属性指令Angular 10中使用 ViewChildren 吗?

问题描述

我的指令:

import {
  AfterViewInit,Directive,ElementRef,HostListener,Input,QueryList,ViewChild,ViewChildren
} from '@angular/core';

@Directive({
  selector: '[appLinks]',})
export class LinksDirective implements AfterViewInit {

  constructor(
    private el: ElementRef,) { }

  @input() defaultColor: string;
  @Input('myHighlight') highlightColor: string;

  @ViewChildren('appLinks',{ read: ElementRef }) appLinks: QueryList<ElementRef>;

  @HostListener('click') onMouseEnter() {
    this.highlight(this.highlightColor || this.defaultColor || 'red');
    console.log('=>[ classLinksDirective//QueryList ]',this.appLinks.first);
  }

  private highlight(color: string) {
    console.log('=>[ class LinksDirective//highlight ]',color);
    this.el.nativeElement.style.backgroundColor = color;
  }
  public ngAfterViewInit() {
    console.log('=>[ classLinksDirective//QueryList ]',this.appLinks.first);
  }
}

我想在我的控制台中有一些东西。在 AfterViewInit 中登录,但什么也没有。

奇怪的是:

console.log('=>[ classLinksDirective//QueryList ]',this.el.nativeElement.id);

返回 id 的列表,但我无法将其推送到数组中。 该指令在 appModule 中声明,并且高亮功能正在工作。目标行为是将所有链接设置为另一种颜色,然后查看活动链接后面的颜色。

我的 HTML 是:

<div class="intro-direct-links">
    <span id="link0" appLinks (click)="slideScreenDirectLink(0)">page0</span>
    <span id="link1" appLinks (click)="slideScreenDirectLink(1)">page1</span>
    <span id="link2" appLinks (click)="slideScreenDirectLink(2)">page2</span>
    <span id="link3" appLinks (click)="slideScreenDirectLink(3)">page3</span>
</div>

如何使用 ViewChildren 获取 ElementRef appLinks 的列表......就像我可以在组件中做的那样。 关键是我可以通过指令标签获得对 ElementRef 目标的引用,但我无法获得所有标签,也不是 QueryList。 感谢帮助

好的,经过 2 天的搜索,我尝试了我发现的东西,但我不满意,这个过程对我来说看起来很繁重。

我已经在我的组件中导入了指令:

import { LinksDirective } from '../../shared/directives/links.directive';

然后我相对于指令声明 ViewChildren :

  @ViewChildren(LinksDirective) appLinks: QueryList<ElementRef>;

在 forEach 中获得我想要的:

ngAfterViewInit(): void {
    this.appLinks.forEach((key: any,index: any) => {
      console.log('=>[ IntroComponent//LinksDirective ]',key.el.nativeElement);
    });

但仍然......我认为这应该是指令的行为,即使我可以在服务中移动所有这些。 所以问题仍然悬而未决 grrrrrrr :)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)