繁体   English   中英

angular指令如何同时操作多个dom?

[英]How to operate multiple doms at the same time with angular directive?

我解决了这个问题,只需< p [appHighlight]="markArray" #mark>111</p >,并在highlight.directive.ts中设置'@Input('appHighlight') mark: Array'。

参考: https : //stackblitz.com/edit/angular-7ewavt

感谢所有回答,并欢迎其他解决方案。


问题描述:

这是 HTML:

<p appHighlight>111</p>
<p appHighlight>222</p>
<p appHighlight>333</p>

这是directive.ts:

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {

  constructor(private el: ElementRef) {
  }

  @HostListener('mouseenter') onMouseEnter() {
    console.log(this.el);   
    // only output current mouse-hover DOM ElementRef
    // but I want to get all DOM's ElementRef whose bound appHighlight
    // in highlight.directive.ts, NOT xxx.component.ts
    // in pursuit of better decouple and reuse.
  }
}

我想要 :

当鼠标悬停在其中一个 DOM 元素上时,所有与 appHighlight 指令绑定的 DOM 都会被触发。

现在的问题是如何让directive.ts,不xxx.component.ts所有绑定元素的DOM ElementRef? (因为追求更好的解耦和重用。)

谢谢。

ViewChildren装饰器为您提供了确切的信息:

export class AppComponent implements AfterViewInit {
  @ViewChildren(HighlightDirective, {read: ElementRef) children: QueryList<ElementRef>;

  // ...

  ngAfterViewInit() {
    this.children.forEach(child => console.log(child.nativeElement));
  }
}

如果您正在寻找指令中的所有元素,那么它不是查看的正确位置。 如果您需要绑定到appHighlight指令的所有元素,那么您应该在父组件中查看。

export class AppComponent  {
    @HostListener('mouseenter') onMouseEnter() {
     this.highlights.forEach(highlight => console.log(highlight));
  }
  @ViewChildren(HighlightDirective, { read: ElementRef }) highlights: QueryList<ElementRef>

  name = 'Angular';
}

在这里,我们现在正在收听mouseenterAppComponent而不是内部HighlightDirective

工作堆栈闪电战

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM