我刚刚在创建了一个空Angular
项目IntelliJ
,试图将文本框绑定到对象的成员。我的物体停留undefined
在里面或我分配给它的任何东西OnInit
。我已包含在内FormsModule
,app.module.ts
但无法正常使用。这是我的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
) {
}
}
我究竟做错了什么?
您的ng-model绑定必须是双向绑定,如下所示:(请注意多余的括号)
<input type="text" name="name" id="name" [(ngModel)]="person.name">
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句