overexchange
overexchange

Reputation: 1

Two way data binding - ngModel

In the below angular2 component,

export class HomeComponent implements OnInit {
  homeTitle = "Welcome to the home page";
  myString = "I like red";
  myBoolean = false;

  alertMe(val){
    alert(val);
  }

  obj = {
    name: "Yoshi",
    belt: "Black"
  };

  constructor() { }

  ngOnInit() {
  }

}

two way data binding does not work for below view,

<p>
  {{homeTitle}}
</p>

<!--  Property binding -->

<!-- input value="Hai" -->
<input [value]="myString">
<input [required]="myBoolean">

<button (click)="alertMe('I like x')">Click me</button>

<hr>
<!-- All above elements are working fine -->

<!-- 2 way data binding -->
<input [(ngModel)]="obj.name">
<p>{{obj.name}}</p>
<p>{{obj.belt}}</p>

Why obj.name does not render in the input element?

Upvotes: 1

Views: 692

Answers (2)

Mohamed Ali RACHID
Mohamed Ali RACHID

Reputation: 3297

in your Module just add FormsModule

import { FormsModule } from '@angular/forms';
imports: [
  ..
  FormsModule
]

Upvotes: 2

Luca Taccagni
Luca Taccagni

Reputation: 1059

sorry, i saw it now.. you have to specify name="myModelName" in input:

like <input name="myModelName" [(ngModel)]="obj.name">

Upvotes: 0

Related Questions