In this article, we will learn how to open the modal popup in another component using Angular 13.
Prerequisites:
- Basic knowledge of Angular
- Code editor like Visual Studio Code
Let us understand with an example.
In this example, there are 2 components one component contains modal code, and the other components contain the open modal button and when you click on the open modal button it opens the modal which is on another component.
First, create a new project using the following command.
ng new openmodal
Then open the project in VS Code and install ng-bootstrap by using the following command.
ng add @ng-bootstrap/ng-bootstrap
Then open styles.css and add the following line to it.
@import '~bootstrap/dist/css/bootstrap.min.css';
Open angular.json and add bootstrap.min.css in it.
"styles": [ "node_modules/bootstrap/dist/css/bootstrap.min.css", "src/styles.css" ]
Create a new component using the following command.
ng g c modal
Open modal.component.html and paste the below code in it.
<div class="modal-header"> <h4 class="modal-title">Hi there!</h4> </div> <div class="modal-body"> <p>Hello</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-outline-dark" (click)="closeModal()">Close</button> </div>
Open modal.component.ts and paste the below code in it.
import { Component, OnInit } from '@angular/core'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; @Component({ selector: 'app-modal', templateUrl: './modal.component.html', styleUrls: ['./modal.component.css'] }) export class ModalComponent implements OnInit { constructor(private activeModal: NgbActiveModal) {} ngOnInit() { } closeModal() { this.activeModal.close('Modal Closed'); } }
Open app.component.ts and paste the below code in it.
import { Component, OnInit } from '@angular/core'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { ModalComponent } from '../modal/modal.component'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { constructor(public modalService: NgbModal) { } openModal() { //ModalComponent is component name where modal is declare const modalRef = this.modalService.open(ModalComponent); modalRef.result.then((result) => { console.log(result); }).catch((error) => { console.log(error); }); } ngOnInit(): void { } }
Open app.component.html and paste the below code in it.
<button (click)="openModal()" class="btn btn-primary">Open Modal</button>
That’s it.
Output:
Also check, Change Color In Component From Other Component In Angular 13