Creating forms inside modals has some great benefits. Using them along with valuable content might bring a lot of attraction to your project. With the emergence of ngx- and ng-bootstrap, we can easily integrate any Bootstrap components to our application.

This article covers the following topics:

Creating a Angular Project

Adding ng-bootstrap and create a simple modal

Adding the form inside of our modal

Summary

So, let’s get started!

Creating The Project

The best way to start a new project, is by using the Angular CLI. The CLI takes care of code-scaffolding of the initial app, building our app, creating of components, and much, much more. To get access to the Angular CLI toolkit, you first need to install it.

Use the following command:

npm install @angular/cli -g

Then initialize a new Angular project with:

ng new ngModalForm

Once it is finish, access the directory and run ng serve . This will serve our application at localhost:4200 . When pasting and enter this snippet in your URL, you should see a basic page.

Adding ng-bootstrap

As I mentioned earlier, we’ll use the ng-bootstrap library in our project. ng-bootstrap is dependent on both Angular and Bootstrap. Since we already have Angular sat up, we only need Bootstrap.

Run the following command:

npm i bootstrap

This will install the package, but we still need to set it up. In your angular-cli.json file, add the following lines in the styles array:

"styles": [

"styles.css",

"../node_modules/bootstrap/dist/css/bootstrap.min.css"

],...

Note! I ran into a issue with the bootstrap version I used (4.0.0-beta.3). You need to downgrade to beta 2 to make it work. Simply update dependency inside package.json and run npm i .

Then install ng-bootstrap with:

npm i --save @ng-bootstrap/ng-bootstrap

Once installed, import the module in the app.module:

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';



@NgModule({

declarations: [AppComponent, ...],

imports: [

NgbModule.forRoot(),

...

],

bootstrap: [AppComponent]

})

export class AppModule {

}

This allows us to simply import NgbModule in other components that wants to use the toolkit of the library.

Adding The Modal

Let’s start by creating a modal with some simple content in it.

Create a new component for the component: ng g c FormModal . This creates the new component and adds it to the module declaration. But we also need to add it in the entryComponents declarations.

...

bootstrap: [AppComponent],

entryComponents: [

FormModalComponent

]

...

The next thing we’ll need to do is registering a service provider for NgbActiveModal inside the FormModalComponent we just created.

import { N gbActiveModal } from '@ng-bootstrap/ng-bootstrap';

We’ll also need to create a reference to the service in our constructor:

constructor(

public activeModal: NgbActiveModal

) { }

And a method for closing for closing the modal and pass some data back to the trigger method.

closeModal() {

this.activeModal.close('Modal Closed');

}

The last thing we need to do with the component, is adding the content in form-modal.component.html .

<div class="modal-header">

<h4 class="modal-title">Modal Title</h4>

<button type="button" class="close" aria-label="Close"

(click)="activeModal.dismiss('Cross click')">

</button>

</div>

<div class="modal-body">

<p>My modal content</p>

</div>

<div class="modal-footer">

<button (click)="activeModal.dismiss('Close clicked')">

Close Clicked

</button>

</div>

So, the modal-component is all set up, but how do we initialize it? We will do this through the app.component.ts file.

Start by importing the NgbModal and FormModalComponent .

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

import { FormModalComponent } from './form-modal/form-modal.component';

Create a reference in the constructor:

constructor(

private modalService: NgbModal

) { }

And a method for initializing the modal.

openFormModal() {

const modalRef = this.modalService.open(FormModalComponent);



modalRef.result.then((result) => {

console.log(result);

}).catch((error) => {

console.log(error);

});

}

Finally, add a button with a click event, attached to it.

<button (click)="openFormModal()">Open Modal</button>

And voilá! Clicking the “Open Modal”-button will launch the modal.

Adding The Form

We want to achieve a couple of things when implementing the form inside our modal.

Pass a id to the form (in case you want to retrieve some editable information).

Pass the result back to the component which triggered the modal.

Start by adding these declarations inside the app.module .

import { FormsModule, ReactiveFormsModule } from '@angular/forms'; ...

imports: [

BrowserModule,

NgbModule.forRoot(),

FormsModule,

ReactiveFormsModule

],

...

We may want to pass an id to the modal-component. This is achieved by adding the following line inside the openFormModal method.

openFormModal() {

const modalRef = this.modalService.open(FormModalComponent);

modalRef.componentInstance.id = 10; // should be the id



modalRef.result.then((result) => {

console.log(result);

}).catch((error) => {

console.log(error);

});

}

Retrieve it in the FormModalComponent , using the Input binding.

import { Component, OnInit, Input } from '@angular/core';

...

@Input id: number;

You now have access to the id inside of the modal.

So let’s add the form.

<div class="modal-header">

<h4 class="modal-title">My Form</h4>

<button type="button" class="close" aria-label="Close"

(click)="activeModal.dismiss('Cross click')">

</button>

</div>

<form [formGroup]="myForm" (ngSubmit)="submitForm()">

<div class="modal-boy">

<div class="container">

<div class="form-group">

<label for="username">Username</label>

<input type="text"

class="form-control"

formControlName="username" />

</div>

<div class="form-group">

<label for="password">Password</label>

<input type="password" class="form-control">

</div>

</div>

</div>

<div class="modal-footer">

<button class="btn btn-success"

[disabled]="!myForm.valid">

Submit Form

</button>

</div>

</form>

And the component.

import { Component, Output, EventEmitter, Input } from '@angular/core';

import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';

import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; @Component({

selector: 'app-form-modal',

templateUrl: './form-modal.component.html'

})

export class FormModalComponent { @Input()id: number;

myForm: FormGroup; constructor(

public activeModal: NgbActiveModal,

private formBuilder: FormBuilder

) {

this.createForm();

} private createForm() {

this.myForm = this.formBuilder.group({

username: '',

password: ''

});

} private submitForm() {

this.activeModal.close(this.myForm.value);

}

}

This will currently log the form-values to the console, but you’ll do what it whatever you wish.

Summary

So we’ve achieved the goal of creating a form inside of our ng-boostrap modal. With this approach, you can pass id’s to the form-component, retrieving editable information. You can also pass the values back to the component that initialized it, updating a table or give the user a response.