In my app, on click of an element I am showing a tooltip that contains additional information. This is available for all elements in a list. I would like to be able to close the expansion on click of anything outside of the tooltip.
The concept is essentially what is covered in this answered question but I need it to work if there are multiple instances of the element. I have attempted using ViewChildren for the elements rather than ViewChild as there are multiple but that doesn't achieve what I'm looking for. I would like to avoid using any packages that are not already available from @angular/core
, rxjs
etc., if possible. See below a simplified and condensed version of what I've attempted with no success so far.
HTML
<li *ngFor="let listItem of listItems;">
<p>
<span *ngIf="showTooltip" class="item-tooltip" #itemTooltip>
Tooltip with {{ listItem.detailed }}
<span (click)="toggleTooltip()">Close</span>
</span>
<span (click)="toggleTooltip()" #tooltipTrigger>{{ listItem.blurb }}</span>
</p>
</li>
TS
@ViewChildren('itemTooltip') itemTooltip: ElementRef;
@ViewChildren('tooltipTrigger') tooltipTrigger: ElementRef;
this.showTooltip = false;
constructor( private renderer: Renderer2) {
this.renderer.listen('window', 'click', (e: Event) => {
if (this.showTooltip && e.target !== this.itemTooltip.nativeElement) {
// never gets to here
console.log(‘click detected’);
this.toggleTooltip();
}
});
}
toggleTooltip() {
const tooltipStatus = this.showTooltip;
if (tooltipStatus = true) {
this.showTooltip = false;
} else if (tooltipStatus = false) {
this.showTooltip = true;
}
}