What is the difference between (ngModel)
and [(ngModel)]
?
I know you’re in a hurry for the answer, but a bit of understanding helps. The answer is:
(ngModel)
causes a 1-way data-binding, whereas[(ngModel)]
ensures a two-way data binding.
So, let’s do it with an example for understanding.
Below is a typical example taken from my Ionic 2 Series of articles:
<ion-content padding> <p> Start typing. myForm FormGroup (which 'subject' and 'message' are controls within) is 2-way binding automatically. </p> <p> Independently, 'subject' is two-way binding, and 'message' one-way binding. </p> <ion-list inset> <form #myForm='ngForm' (ngSubmit)="onSubmit(myForm)"> <ion-item> <ion-label floating>Subject</ion-label> <ion-input type="text" [(ngModel)]="subject" name="subject"></ion-input> </ion-item> <ion-item> <ion-label floating>Message</ion-label> <ion-textarea type="text" [ngModel]="message" name="message"></ion-textarea> </ion-item> <button block> <ion-icon name="add"></ion-icon>Submit</button> </form> </ion-list> <p> 'myForm' FormGroup 2-way binding: {{ myForm.value | json }} </p> <h5>This is two-way bound</h5> Subject (updates when typing): "{{ subject }}" <h5>This is one-way bound</h5> Message (doesn't update when typing): "{{ message }}" <h4 *ngIf="subData">I show after Submission</h4> <p *ngIf="subData">Message After Submit: "{{ subData.message }}"</p> </ion-content>
Our associated controller might look like this:
import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; @Component({ templateUrl: 'build/pages/basicform/basicform.html', }) export class BasicformPage { myData: any; subData: any; constructor(private navCtrl: NavController) { } onSubmit(formData) { if(formData.valid) { console.log(formData.value); this.subData = formData.value; } } }
See in action:
https://youtu.be/ccoUMJ5diRI