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?
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">