Angular how to use ngModel correctly? Why I get undefined and errors?

1k views Asked by At

I'm having some issues with this code, Angular logs "undefined" when I use the input field, its a basic component, but can't make it work.

HTML template:

<h1>{{ titulo }}</h1>
<ul>
  <li>hlelo</li>
  <li>hlelo</li>
  <li>hlelo</li>
  <li>hlelo</li>
  <li>hlelo</li>
</ul>

Nombre del parque:

<input type="text" [(ngModel)]="nombreDelParque" (keyup)="mostrarNombre()" />

// this is not binding --> 

Resultado {{ nombreDelParque }}

<br />

<parques></parques>

TS file:

import { Component, Input } from '@angular/core';
 
@Component({
  selector: 'tienda',
  templateUrl: './tienda.component.html',
  styleUrls: ['./tienda.component.css'],
})
export class TiendaComponent {
  public titulo: string;
  public nombreDelParque: string;
 
  constructor() {
    this.titulo = 'esta es la tienda';
  }
 
  mostrarNombre() {
    console.log(this.nombreDelParque);
  }
}

Error message in chrome's browser console and when using the input field I get logged undefined on the console.

Error: src/app/components/tienda/tienda.component.html:18:20 - error NG8002:  
 Can't bind to 'ngModel' since it isn't a known property of 'input'.
        
18 <input type="text" [(ngModel)]="nombreDelParque" (keyup)="mostrarNombre()" />
                              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        
src/app/components/tienda/tienda.component.ts:5:16
5   templateUrl: './tienda.component.html',
                             ~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component TiendaComponent.
1

There are 1 answers

1
atin On BEST ANSWER

You have to import FormsModule in app.module.ts to use ngModal. Also if you are using formbuilder you'll need ReactiveFormsModule for that. Don't forget to add these modules to import list.
Here is how your app.module.ts should look:

// your modules
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'; 
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    // your modules
    FormsModule,
    ReactiveFormsModule
  ], 
  declarations: []
  }
)