I have a modal component supplied through a service to my parent component. The modal has an output that seems like should trigger an event that passes a string.
I'm just trying to run some code if the modal is confirmed, but I haven't been able to hook into the event that's supposedly emitted. What am I missing?
[ modal.component.ts ]
export class ModalComponent implements OnInit {
...
@Output() onAccepted = new EventEmitter<string>();
@Output() onDeclined = new EventEmitter<string>();
@Input() id!: string;
private element: any;
constructor(private modalService: ModalService, private el: ElementRef) {
this.element = el.nativeElement;
}
ngOnInit(): void {
// ensure id attribute exists
if (!this.id) {
console.error('modal must have an id');
return;
}
// add self (this modal instance) to the modal service so it's accessible from controllers
this.modalService.add(this);
}
accept()
{
this.onAccepted.emit("Accepted");
this.close();
}
...
// remove self from modal service when component is destroyed
ngOnDestroy(): void {
this.modalService.remove(this.id);
this.element.remove();
}
}
[ modal.service.ts ]
@Injectable({ providedIn: 'root' })
export class ModalService {
private modals: any[] = [];
add(modal: any) {
// add modal to array of active modals
this.modals.push(modal);
}
remove(id: string) {
// remove modal from array of active modals
this.modals = this.modals.filter(x => x.id !== id);
}
open(id: string) {
// open modal specified by id
const modal = this.modals.find(x => x.id === id);
modal.open();
}
close(id: string) {
// close modal specified by id
const modal = this.modals.find(x => x.id === id);
modal.close();
}
}
[modal-parent.component.html]
<modal id="assignAdminModal" title="Assign Administrator role" [message]="'Confirm assigning Administrator rights to this user?'"
[showDecline]="true" [showAccept]="true" (onAccepted)="test($event)"></frisbo-modal>
[modal-parent.component.ts]
test(event: any): void {
console.log(event);
}