简体   繁体   English

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

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

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

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

Thanks for all answer, and welcome other solutions.感谢所有回答,并欢迎其他解决方案。


Question Desc:问题描述:

This is HTML:这是 HTML:

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

This is directive.ts:这是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.
  }
}

I want :我想要 :

When the mouse is hover one of the DOM elements, all DOMs bound with the appHighlight instruction are triggered.当鼠标悬停在其中一个 DOM 元素上时,所有与 appHighlight 指令绑定的 DOM 都会被触发。

The question is how to get the DOM ElementRef of all bound elements in directive.ts , NOT xxx.component.ts ?现在的问题是如何让directive.ts,不xxx.component.ts所有绑定元素的DOM ElementRef? (because in pursuit of better decouple and reuse.) (因为追求更好的解耦和重用。)

Thanks.谢谢。

the ViewChildren decorator gives you exactly that: ViewChildren装饰器为您提供了确切的信息:

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

  // ...

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

If you are looking for all the elements inside the directive then it is not the right place to look into.如果您正在寻找指令中的所有元素,那么它不是查看的正确位置。 If you need all the elements which are bound to appHighlight directive then you should look that in the parent component.如果您需要绑定到appHighlight指令的所有元素,那么您应该在父组件中查看。

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

  name = 'Angular';
}

Here we are now listening to mouseenter in AppComponent rather than inside HighlightDirective .在这里,我们现在正在收听mouseenterAppComponent而不是内部HighlightDirective

Working Stackblitz工作堆栈闪电战

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

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