gpt4 book ai didi

javascript - 如何使用 Angular 指令同时操作多个 dom?

转载 作者:行者123 更新时间:2023-11-28 03:18:00 25 4
gpt4 key购买 nike

我解决了这个问题,只需

111

,并在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>

这是指令.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 指令绑定(bind)的 DOM 都会被触发。

问题是如何获取 directive.ts 中所有绑定(bind)元素的 DOM ElementRef,而不是 xxx.component.ts ? (因为追求更好的解耦和复用。)

谢谢。

最佳答案

ViewChildren装饰器给你的正是这样的:

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

// ...

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

关于javascript - 如何使用 Angular 指令同时操作多个 dom?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59464909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com