【问题标题】:Data Binding with [ngModel] not working Angular 6与 [ngModel] 的数据绑定不起作用 Angular 6
【发布时间】: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
  ) {
  }
}

我做错了什么?

【问题讨论】:

标签: angular ngmodel


【解决方案1】:

您的 ng-model 绑定必须是双向绑定,如下所示: (注意多余的括号)

<input type="text" name="name" id="name" [(ngModel)]="person.name">

【讨论】:

  • 这类问题是最糟糕的。很高兴我能帮上忙。
  • 这很尴尬,谢谢。它节省了我的时间
【解决方案2】:

你可以看这里:https://angular.io/api/forms/NgModel

在您的情况下,您可以通过这种方式更正app.component.html 的代码:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-27
    • 2019-01-06
    • 2017-12-05
    • 2016-10-12
    • 2015-10-15
    相关资源
    最近更新 更多