3

I just created an empty Angular project on IntelliJ, I'm trying to bind a textbox to an object's member. My object stays undefined or whatever I assign to it inside OnInit. I included FormsModule in the app.module.ts and I can't get it to work. This is my app.component.html file:

<form #form="ngForm">
    <input type="text" name="name" id="name" [ngModel]="person.name">
    <button (click)="save()">save</button>
</form>

This is app.component.ts:

import {Component, OnInit} from '@angular/core';
import {IPerson, Person} from './model/person.model';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'my-app';
  names?: string;
  person?: IPerson;

  save() {
    console.log('::::::' + this.person.name);
  }

  ngOnInit(): void {
   this.person = new Person();
  }
}

app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import {FormsModule} from "@angular/forms";

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

and this is person.model.ts:

export interface IPerson {
  name?: string;
}

export class Person implements IPerson {
  constructor(
    public name?: string
  ) {
  }
}

What am I doing wrong?

1

2 Answers 2

6

your ng-model binding has to be a two-way binding like so: (notice the extra parentheses)

<input type="text" name="name" id="name" [(ngModel)]="person.name">
2
  • These kind of problems are the worst. Glad I could help.
    – leawp
    Mar 31, 2019 at 17:01
  • This is quite embarrassing, Thank you. It saved my time
    – Iswar
    Nov 25, 2019 at 5:55
0

You can look here :https://angular.io/api/forms/NgModel

in your case you can correct the code of app.component.html in this way :

<form #form="ngForm">
    <input type="text" name="name" id="name" [(ngModel)]="person.name">
    <button (click)="save()">save</button>
</form>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.