29
loading...
This website collects cookies to deliver better user experience
Modal service which is responsible for creating/destroying modal.
Modal component containing modal information ( body, title, buttons ) and, it sends events to modalService ( confirm/close ).
Hosting component contains a reference to where the modal is going to appear and listen to modalService events. It does not know anything about the modal.
viewContainerRef represents a container where one or more views can be attached to a component.
componentFactoryResolver is a simple registry that maps Components to generated ComponentFactory classes that can be used to create instances of components.
ComponentFactory is the base class for a factory that can create a component dynamically. Instantiate a factory for a given type of component with resolveComponentFactory().
export class ModalService {
private componentRef!: ComponentRef<ModalComponent>;
private componentSubscriber!: Subject<string>;
constructor(private resolver: ComponentFactoryResolver) {}
openModal(entry: ViewContainerRef, modalTitle: string, modalBody: string) {
let factory = this.resolver.resolveComponentFactory(ModalComponent);
this.componentRef = entry.createComponent(factory);
this.componentRef.instance.title = modalTitle;
this.componentRef.instance.body = modalBody;
this.componentRef.instance.closeMeEvent.subscribe(() => this.closeModal());
this.componentRef.instance.confirmEvent.subscribe(() => this.confirm());
this.componentSubscriber = new Subject<string>();
return this.componentSubscriber.asObservable();
}
closeModal() {
this.componentSubscriber.complete();
this.componentRef.destroy();
}
confirm() {
this.componentSubscriber.next('confirm');
this.closeModal();
}
}
export class ModalComponent implements OnInit, OnDestroy {
constructor() {}
@Input() title: string = '';
@Input() body: string = '';
@Output() closeMeEvent = new EventEmitter();
@Output() confirmEvent = new EventEmitter();
ngOnInit(): void {
console.log('Modal init');
}
closeMe() {
this.closeMeEvent.emit();
}
confirm() {
this.confirmEvent.emit();
}
ngOnDestroy(): void {
console.log(' Modal destroyed');
}
}
@viewChild is a property decorator that configures a view query. The change detector looks for the first element or the directive matching the selector in the view DOM
export class HomeComponent implements OnInit, OnDestroy {
constructor(private modalService: ModalService) {}
@ViewChild('modal', { read: ViewContainerRef })
entry!: ViewContainerRef;
sub!: Subscription;
ngOnInit(): void {}
createModal() {
this.sub = this.modalService
.openModal(this.entry, 'Are you sure ?', 'click confirm or close')
.subscribe((v) => {
//your logic
});
}
ngOnDestroy(): void {
if (this.sub) this.sub.unsubscribe();
}
}
<button (click)="createModal()">Delete me</button>
<div #modal></div>