【发布时间】:2020-05-26 00:44:19
【问题描述】:
我刚刚在IntelliJ 上创建了一个空的Angular 项目,我正在尝试将一个文本框绑定到一个对象的成员。我的对象保留在undefined 或我在OnInit 中分配给它的任何内容。我在app.module.ts 中加入了FormsModule,但我无法让它工作。
这是我的app.component.html 文件:
<form #form="ngForm">
<input type="text" name="name" id="name" [ngModel]="person.name">
<button (click)="save()">save</button>
</form>
这是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 { }
这是person.model.ts:
export interface IPerson {
name?: string;
}
export class Person implements IPerson {
constructor(
public name?: string
) {
}
}
我做错了什么?
【问题讨论】: