JustisBogus
JustisBogus

Reputation: 73

ngModel does not work in the input field

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 = '';
}

Upvotes: 5

Views: 18298

Answers (3)

leopal
leopal

Reputation: 4959

To use ngModel you should firstly import it.

In the app.module.ts, just add:

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

[...]

@NgModule({
  imports: [
    [...]
    FormsModule
  ],
  [...]
})

Upvotes: 14

Pardeep Jain
Pardeep Jain

Reputation: 86720

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.

Upvotes: 3

NitinSingh
NitinSingh

Reputation: 2068

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

Upvotes: 3

Related Questions