【问题标题】:Why doesnt two-way binding [(ngModel)] work in Angular 2.1.1?为什么双向绑定 [(ngModel)] 在 Angular 2.1.1 中不起作用?
【发布时间】:2017-03-23 19:50:50
【问题描述】:

当我尝试使用时:

<input [(ngModel)]="model.name" >

我的代码中断,我收到以下错误:

Error: Template parse errors:

但是,当我以不同的方式实现双向绑定时,它可以工作。

这是有效的代码:

<input [value]="model.name" (input)="model.name=$event.target.value">

我正在按照位于https://angular.io/docs/ts/latest/guide/template-syntax.html#!#two-way的说明进行操作

有谁知道这是 Angular 当前 RC 中的错误还是我做错了什么?

这是所要求的错误截图:

(anonymous function)    @   main.bundle.js:39182
ZoneDelegate.invoke @   zone.js:232
Zone.run    @   zone.js:114
(anonymous function)    @   zone.js:502
ZoneDelegate.invokeTask @   zone.js:265
Zone.runTask    @   zone.js:154
drainMicroTaskQueue @   zone.js:401
ZoneTask.invoke @   zone.js:339

这是我的 app.module.ts 文件的样子:

import { NgModule, ApplicationRef } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { removeNgStyles, createNewHosts, createInputTransfer } from '@angularclass/hmr';

/*
 * Platform and Environment providers/directives/pipes
 */
import { ENV_PROVIDERS } from './environment';
import { routing } from './app.routing';

// App is our top level component
import { App } from './app.component';
import { AppState, InternalStateType } from './app.service';
import { GlobalState } from './global.state';
import { NgaModule } from './theme/nga.module';
import { PagesModule } from './pages/pages.module';

// import { JpsInputComponent } from './theme/components/jps-input/jps-input.component';

import { SharedModule } from './shared/shared.module';

// Application wide providers
const APP_PROVIDERS = [
  AppState,
  GlobalState
];

type StoreType = {
  state: InternalStateType,
  restoreInputValues: () => void,
  disposeOldHosts: () => void
};

/**
 * `AppModule` is the main entry point into Angular2's bootstraping process
 */
@NgModule({
  bootstrap: [App],
  declarations: [
    App,
    // JpsInputComponent
  ],
  imports: [ // import Angular's modules
    BrowserModule,
    HttpModule,
    RouterModule,
    FormsModule,
    ReactiveFormsModule,
    NgaModule.forRoot(),
    PagesModule,
    SharedModule,
    routing
  ],
  providers: [ // expose our Services and Providers into Angular's dependency injection
    ENV_PROVIDERS,
    APP_PROVIDERS
  ],
  exports: [
    // JpsInputComponent
  ]
})

export class AppModule {

  constructor(public appRef: ApplicationRef, public appState: AppState) {
  }

  hmrOnInit(store: StoreType) {
    if (!store || !store.state) return;
    console.log('HMR store', JSON.stringify(store, null, 2));
    // set state
    this.appState._state = store.state;
    // set input values
    if ('restoreInputValues' in store) {
      let restoreInputValues = store.restoreInputValues;
      setTimeout(restoreInputValues);
    }
    this.appRef.tick();
    delete store.state;
    delete store.restoreInputValues;
  }

  hmrOnDestroy(store: StoreType) {
    const cmpLocation = this.appRef.components.map(cmp => cmp.location.nativeElement);
    // save state
    const state = this.appState._state;
    store.state = state;
    // recreate root elements
    store.disposeOldHosts = createNewHosts(cmpLocation);
    // save input values
    store.restoreInputValues = createInputTransfer();
    // remove styles
    removeNgStyles();
  }

  hmrAfterDestroy(store: StoreType) {
    // display new elements
    store.disposeOldHosts();
    delete store.disposeOldHosts;
  }
}

这是组件模板文件:

<form>
  <div class="input-group">
    <input type="text" class="form-control with-danger-addon">
    <span class="input-group-btn">
        <button class="btn btn-danger" type="submit">Go!</button>
    </span>
  </div>

  {{ model.name }}

  <input [(ngModel)]="model.name">


</form>

这是组件打字稿文件:

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

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

    model = {
      name: 'This is the persons name'
    };

    constructor() {

    }

    ngOnInit() {
        console.log('Number Intake System Loaded');
    }


}

我以这个项目为基础: https://github.com/akveo/ng2-admin

【问题讨论】:

  • 请把整个错误贴出来,Template parse errors:之后是什么意思?
  • @StefanSvrkota,我添加了控制台错误的屏幕截图,并以文本形式添加了错误。
  • 请同时发布您的模板。
  • @StefanSvrkota,再次更新
  • @StefanSvrkota,用新的发现和一些额外的困惑再次更新了帖子!请帮忙!

标签: angular data-binding binding


【解决方案1】:

您的输入元素需要一个名称。来自https://angular.io/docs/ts/latest/guide/forms.html

在使用 [(ngModel)] 时,需要定义名称属性 与表格结合

【讨论】:

  • 嘿@fiddles,虽然你的回答是正确的,但它恰好不是问题的症结所在。我采纳了您的建议,并为您的帮助投了赞成票。
【解决方案2】:

我怀疑您忘记将 FormsModule 导入当前的 NgModule。 ngModel 默认不可用。

import {FormsModule} from '@angular/forms';
import {NgModule} from '@angular/core';
@NgModule({
    declarations: [
        ...
    ],
    imports: [
        FormsModule,
        BrowserModule,
    ],
    bootstrap: [...]
})
export class AppModule {
}

【讨论】:

  • 我试过你的代码,它运行良好。也请与我们分享您的组件。
  • 再次为您更新了其他组件文件
  • 你确定这是好的吗?因为在你的模块中,组件JpsInputComponent 没有被声明。它被评论了
  • 我再次更新了这篇文章,虽然我得到了它的工作,但我觉得它仍然不是“正确”的解决方案。如果你有时间看看,如果你能帮助解决我对如何在项目中导入模块/组件的任何剩余困惑,请告诉我。
猜你喜欢
  • 2017-10-20
  • 2015-10-15
  • 2020-09-12
  • 2017-04-29
相关资源
最近更新 更多