I made a Stackblitz for my code (link: https://stackblitz.com/edit/angular-iah7up ). This is my custom component that toggles two ng-content based on click in and clicks out.
import {Component, ElementRef, EventEmitter, OnDestroy, OnInit, Output} from '@angular/core';
import {fromEvent, Subject} from "rxjs";
import {untilDestroyed} from "ngx-take-until-destroy";
import {filter, switchMapTo, take} from "rxjs/operators";
@Component({
selector: 'app-editable-inplace',
templateUrl: './editable-inplace.component.html',
styleUrls: ['./editable-inplace.component.css']
})
export class EditableInplaceComponent implements OnInit, OnDestroy {
@Output() update = new EventEmitter();
mode: 'view' | 'edit' = 'view';
editMode = new Subject();
editMode$ = this.editMode.asObservable();
ngOnInit(): void {
this.viewModeHandler();
this.editModeHandler();
}
constructor(private host: ElementRef) {
}
// This method must be present, even if empty.
ngOnDestroy() {
// To protect you, we'll throw an error if it doesn't exist.
}
private viewModeHandler() {
fromEvent(this.element, 'click').pipe(
untilDestroyed(this)
).subscribe(() => {
console.log('clicked inside')
this.editMode.next(true);
this.mode = 'edit';
});
}
private editModeHandler() {
const clickOutside$ = fromEvent(document, 'click').pipe(
filter(({target}) => {
console.log(this.mode)
console.log('parent', this.element, 'child', target)
const ans = this.element.contains(target) === false
console.log('clickoutside', ans)
return ans
}),
take(1)
)
this.editMode$.pipe(
switchMapTo(clickOutside$),
untilDestroyed(this)
).subscribe(event => {
this.update.next();
this.mode = 'view';
});
}
get element() {
return this.host.nativeElement;
}
toViewMode() {
this.update.next();
this.mode = 'view';
}
}
Template:
<div *ngIf="mode==='view'" >
<ng-content select="[view]"></ng-content>
</div>
<div *ngIf="mode==='edit'" >
<ng-content select="[edit]"></ng-content>
</div>
Usage:
<app-editable-inplace >
<div view>
<h3>Click to edit [not working :-( ]</h3>
</div>
<div edit>
<input placeholder="Click to edit" >
</div>
</app-editable-inplace>
But When I click on the view, clickOutside$ is triggered instantly (I don't know why)
And also, the line this.element.contains(target) === false is not working because I can see in the console that the host contains the clicked item although always say that I clicked outside (I don't know why too)
