I have many components that are on top of each other, and I need to add a listener so when a mouse pointer is in bounds of these components every component will do something.
I tried with mouseover, mouseenter, mousemove, etc. but these events works only on the component that is on top, not on all of them. ex html:
<div class="container">
<app-child></app-child>
<app-child></app-child>
<app-child></app-child>
<app-child></app-child>
</div>
ex css:
.container > * {
position: absolute;
left: 0;
top: 0;
width: 100px;
height: 100px;
border: 1px solid black;
}
ex app-child.component.ts
@Component({
selector: 'app-child',
template: '<div></div>'
})
ChildComponent {
// Here some function that needs to run if mouse pointer is in bound of this element
}
if you want the children to do something
parent.component.html
<div class="container" (mouseenter)="doSomethingFunction()" (mouseleave)="stopDoSomething()>
<app-child [doSomething]="doSomething"></app-child>
<app-child [doSomething]="doSomething"></app-child>
<app-child [doSomething]="doSomething"></app-child>
<app-child [doSomething]="doSomething"></app-child>
</div>
parent.component.ts
@Component({
selector: 'app-child',
template: '<div></div>'
})
ParentComponent {
doSomething = false;
doSomethingFunction(e) {
doSomething = true;
}
stopDoSomething(e) {
doSomething = false;
}
}
child.component.ts
@Component({
selector: 'app-child',
template: '<div></div>'
})
ChildComponent {
@Input() doSomething: boolean
ngOnInit() {
if(doSomething) {
doSomethingElse();
} else {
stopDoingThings();
}
}
}
if you have to do something to the children
parent.component.html
<div class="container" (mouseenter)="doSomething($event)">
<app-child></app-child>
<app-child></app-child>
<app-child></app-child>
<app-child></app-child>
</div>
parent.component.ts
@Component({
selector: 'app-child',
template: '<div></div>'
})
ParentComponent {
doSomething(e) {
for(const child in Array.from(e.target.children) {
doSomethingElse(child);
}
}
}