I am currently attempting to enable inline editing for an input field by incorporating a clickOutside directive. The issue I am facing is that when I click on the element to edit, the editMode
variable becomes true, displaying the input immediately. However, the clickOutside
event triggers right away, causing the editMode
to become false and preventing my edit action from working properly:
<span *ngIf="!editMode" (click)="edit(); editMode = true"></span>
<input *ngIf="editMode" (clickOutside)="save(); editMode = false">
How can I address this issue effectively? Your assistance is greatly appreciated.
Below is the code for my clickOutside directive:
import {Directive, ElementRef, Output, EventEmitter, HostListener} from '@angular/core';
@Directive({
selector: '[clickOutside]'
})
export class ClickOutsideDirective {
constructor(private elementRef: ElementRef) {
}
@Output()
public clickOutside = new EventEmitter<MouseEvent>();
@HostListener('document:click', ['$event', '$event.target'])
public onClick(event: MouseEvent, targetElement: HTMLElement): void {
if (!targetElement) {
return;
}
const clickedInside = this.elementRef.nativeElement.contains(targetElement);
if (!clickedInside) {
this.clickOutside.emit(event);
}
}
}