ngx-modal - Angular 2

6.4k views Asked by At

I am trying to implement modal form in my angular application. My code looks alright to me as i do not see any error. I have installed ngx-modal into my application and i have also imported the ModalModule in my app.module.ts file. What could be the reason why the modal form is not responding?

<button class="btn btn-success"  data-toggle="modal" data-target="#myModal">Open</button>

<div class="modal fade" id="myModal" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">

          <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body">
</div>
      </div>
    </div>
  </div>
</div>

app.module.ts

import {ModalModule} from 'ngx-modal';

imports: [          
        ModalModule,
],
2

There are 2 answers

4
Roman C On BEST ANSWER

you have required to open your modal with

<button (click)="myModal.open()">open my modal</button>
<modal #myModal>
    <modal-header>
        <h1>Modal header</h1>
    </modal-header>
    <modal-content>
        Hello Modal!
    </modal-content>
    <modal-footer>
      <button class="btn btn-primary" (click)="myModal.close()">&times;</button>
    </modal-footer>
</modal>
1
Aravind On

Following are your mistakes

  1. You are trying to use the below line similar to the Traditional Bootstrap Modal, which is wrong as the usual one works with jQuery and Bootstrap.js

    <button class="btn btn-success" data-toggle="modal" 
             data-target="#myModal">Open</button>
    
  2. You are using id to define a name to the modal component which is also invalid in the case of typescript and angular2

    <div class="modal fade" id="myModal" role="dialog">
    

Solution: Replacing the lines in the below code, will work as expected for ngx-modal.

import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {ModalModule} from "ngx-modal";
@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <div class="row">
    <button (click)="myModal.open()">open my modal</button>
    <modal #myModal>
        <modal-header>
            <h1>Modal header</h1>
        </modal-header>
        <modal-content>
            Hello Modal!
        </modal-content>
        <modal-footer>
            <button class="btn btn-primary" (click)="myModal.close()">close</button>
        </modal-footer>
    </modal>
</div>
    </div>
  `,
})
export class App {
  name:string;
  constructor() {
    this.name = 'Angular2'
  }
}

@NgModule({
  imports: [ BrowserModule,ModalModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

LIVE DEMO