【问题标题】:Two Way Data Binding - Angular 2双向数据绑定 - Angular 2
【发布时间】:2017-01-21 22:00:45
【问题描述】:

我正在尝试使用 ngModel 进行双向数据绑定,但它不起作用。 包括 FormsModule。 这里是代码:

app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { TestComponent } from './test/test.component';

@NgModule({
  declarations: [
    TestComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

test.component.ts:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

  person = {
    name: 'David',
    age: '17'
  };

  constructor() { }

  ngOnInit() {
  }

}

test.component.html:

<form>
  <input type="text" [(ngModel)]="person.name" />
  <input type="text" [(ngModel)]="person.age" />
</form>

{{person.name}}<br />
{{person.age}}

为什么它不起作用?

谢谢。

【问题讨论】:

  • 您的控制台有错误吗?您必须按照凯姆斯基的建议将名称添加到您的输入中

标签: angular


【解决方案1】:

您必须将name 属性添加到输入。

【讨论】:

    【解决方案2】:

    其他方法是添加

    [ngModelOptions]="{standalone: true}" 
    

    他明白他不是表格的一部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-29
      • 2017-03-17
      • 2017-01-20
      • 2017-03-06
      • 2016-10-12
      • 2017-04-29
      • 2017-12-15
      相关资源
      最近更新 更多