Angular 6 - display component as modal dialog from

2019-07-10 01:58发布

I am attempting to display a modal confirmation popup after I perform a submit action from my component.

The onSubmit() method in my home.component.ts:

onSubmit() {
    var response = new Response(1, this.name, this.phone, this.email, 
    this.optIn, this.responses);
    this.questionsService.saveResponse(response).subscribe(
         data => response = data)

    // show popup confirmation dialog here

    this.ngOnInit();
}

My confirmation-modal component: import { Component, Input } from '@angular/core';

import { NgbModal, NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
    selector: 'confirmation-modal',
    templateUrl: './confirmation-modal.html'
})

export class ConfirmationModal {
    modalRef;

    constructor(private modalService: NgbModal) {
    }

    open(content) {
       this.modalRef = this.modalService.open(content, { centered: true, 
        size: 'sm' });
    }

    onClose() {
        this.modalRef.close();
    }
}

My component-modal.html is a regular ng-bootstrap HTML template. So, the question is, how can I open the confirmation-modal dialog from the onSubmit() method? I realize I can use a service, but any examples?

Thanks.

1条回答
霸刀☆藐视天下
2楼-- · 2019-07-10 02:37

Most people would put this code inside the parent's submit method:

this.modalRef = this.modalService.open(ConfirmationModal, { centered: true, 
    size: 'sm' });

Notice the use of ConfirmationModal in above code.

You would also need to move the close logic to the parent.

However, I can see that you are trying to go for something more reusable.

What you need to do is call the open method from your home.component

To call a child method in a parent/child relationship is easy using @ViewChild

Docs are here: https://angular.io/guide/component-interaction#parent-calls-an-viewchild

However, I'm not sure this is a parent/child relationship so I'm not sure how much success you will have. You may be forced to fall back to putting the code inside the parent's submit method. Let me know if you find another way, I would be interested to hear.

查看更多
登录 后发表回答