I solved this problem, just < p [appHighlight]="markArray" #mark>111< /p >, and set '@Input('appHighlight') mark: Array' in highlight.directive.ts.
refer to: https://stackblitz.com/edit/angular-7ewavt
Thanks for all answer, and welcome other solutions.
Question Desc:
This is HTML:
<p appHighlight>111</p>
<p appHighlight>222</p>
<p appHighlight>333</p>
This is 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.
The question is how to get the DOM ElementRef of all bound elements in directive.ts , NOT xxx.component.ts ? (because in pursuit of better decouple and reuse.)
Thanks.
the ViewChildren decorator gives you exactly that:
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.
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
.
Working Stackblitz
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.