5

I'm just starting with Angular and trying a simple thing. Angular should update DOM when I type a name in the input field. However when I use these brackets [] like [(ngModel)] not only does it not work, but the input field disappears from the DOM. Without these [] brackets it does not work either. Please help

app.component.html file

 input type="text" [(ngModel)] = "name">
 <p>{{ name }}</p> 

app.component.ts file

import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: '.app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = '';
}
JustisBogus
  • 73
  • 1
  • 2
  • 6
  • Check this post https://stackoverflow.com/questions/43298011/angular-error-cant-bind-to-ngmodel-since-it-isnt-a-known-property-of-inpu/61123200#61123200 – Avinash Apr 09 '20 at 14:16

3 Answers3

13

To use ngModel you should firstly import it.

In the app.module.ts, just add:

import { FormsModule } from '@angular/forms';

[...]

@NgModule({
  imports: [
    [...]
    FormsModule
  ],
  [...]
})
leopal
  • 4,711
  • 1
  • 25
  • 35
3

1) The < symbol is missing from the input tag

2) The property "name" has to be made as public in order to access that in the view

NitinSingh
  • 2,029
  • 1
  • 15
  • 33
2

You probably asking for "How Binding works"

([(ngModel)]) = Also called banana in the box

  • If you are using only [] it means you are just binding value which is called attribute binding

  • If you are using only () It means it is just event binding and fire event on change,click etc .

In case you are using both, it means two-way binding in Angular. it will Update the value into DOM as well as your controller side.

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215