Kihats
Kihats

Reputation: 3520

Two way binding variable in Modal - Angular

I have a Bootstrap Modal that I initialize using jQuery as follows:

$('#saleModal').modal('show'); // I know I should use the angular way in initializing the modal but...

In the Modal I have an input that I need to bind to a variable as follows:

<input type="text" [(ngModel)]="toBeBoundVariable">

But the binding does not work. How can I tell Angular to check for bindings in that Modal.

My best guess for the reason why it's not binding is because the Modal was initialized using jQuery. But, is there a way to tell Angular, "Hey, there is a Bootstrap Modal initialized, there are some bindings you need to be aware of".

Here is the code:

<!--Modal start-->
 <div class="modal" id="saleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel_4"
 aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel_4">New/Edit Sale</h5>
         <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true"><i class="ion-ios-close-empty"></i></span>
        </button>
      </div>
  <form>

    <div class="modal-body">

      <label class="col-sm-4 form-control-label">Name</label>
      <div class="col-sm-8 mg-t-10 mg-sm-t-0">
        <input type="text" class="form-control" [(ngModel)]="firstname">
      </div>
      Bound firstname: {{firstname}}
    </div>

    <div class="modal-footer">
      <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      <button type="submit" class="btn btn-primary"
      >
        <i></i>Save
      </button>
    </div>
  </form>
</div>

.ts file

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

declare var $: any;

@Component({
  selector: 'app-purchase',
  templateUrl: './purchase.component.html',
  styleUrls: ['./purchase.component.css']
})
export class PurchaseComponent implements OnInit {

  firstname: string;

  constructor() {


  }

  ngOnInit() {

  }


  showModal() {
   $('#saleModal').modal('show');
  }


}

Upvotes: 0

Views: 2206

Answers (1)

Nithya Rajan
Nithya Rajan

Reputation: 4884

I think you have missed to add name attribute in your input field.

  <input type="text" class="form-control" [(ngModel)]="firstname" name="firstName">

Hope, it solves your problem. Make sure you have imported the FormsModule in your module.

Upvotes: 1

Related Questions