带有[ngModel]的数据绑定无法正常工作Angular 6

单体

我刚刚在创建了一个空Angular项目IntelliJ,试图将文本框绑定到对象的成员。我的物体停留undefined在里面或我分配给它的任何东西OnInit我已包含在内FormsModuleapp.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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章