简体   繁体   English

Angular 2 使用 ngModel 的双向绑定不起作用

[英]Angular 2 two way binding using ngModel is not working

Can't bind to 'ngModel' since it isn't a know property of the 'input' element and there are no matching directives with a corresponding property无法绑定到“ngModel”,因为它不是“input”元素的已知属性,并且没有具有相应属性的匹配指令

Note: im using alpha.31注意:我使用的是 alpha.31

import { Component, View, bootstrap } from 'angular2/angular2'

@Component({
    selector: 'data-bind'
})
@View({
    template:`
        <input id="name" type="text" 
            [ng-model]="name" 
            (ng-model)="name = $event" />
        {{ name }}
    ` 
})
class DataBinding { 
    name: string;

    constructor(){
        this.name = 'Jose';
    }
}

bootstrap(DataBinding);

Angular has released its final version on 15th of September. Angular 已于 9 月 15 日发布了其最终版本。 Unlike Angular 1 you can use ngModel directive in Angular 2 for two way data binding, but you need write it in a bit different way like [(ngModel)] ( Banana in a box syntax ).与 Angular 1 不同,您可以在 Angular 2 中使用ngModel指令进行双向数据绑定,但您需要以一种有点不同的方式编写它,例如[(ngModel)]Banana in a box syntax )。 Almost all angular2 core directives doesn't support kebab-case now instead you should use camelCase .几乎所有 angular2 核心指令现在都不支持 kebab kebab-case而你应该使用camelCase

Now ngModel directive belongs to FormsModule , that's why you should import the FormsModule from @angular/forms module inside imports metadata option of AppModule (NgModule).现在ngModel指令属于FormsModule ,这就是为什么你要importFormsModule@angular/forms模块内imports的元数据选项AppModule (NgModule)。 Thereafter you can use ngModel directive inside on your page.此后,您可以在页面内部使用ngModel指令。

app/app.component.ts应用程序/app.component.ts

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

@Component({
  selector: 'my-app',
  template: `<h1>My First Angular 2 App</h1>
    <input type="text" [(ngModel)]="myModel"/>
    {{myModel}}
  `
})
export class AppComponent { 
  myModel: any;
}

app/app.module.ts应用程序/app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent }   from './app.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule ], //< added FormsModule here
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})

export class AppModule { }

app/main.ts应用程序/main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);

Demo Plunkr 演示 Plunkr

Key Points:关键点:

  1. ngModel in angular2 is valid only if the FormsModule is available as a part of your AppModule.只有当 FormsModule 作为 AppModule 的一部分可用时,angular2 中的 ngModel 才有效。

  2. ng-model is syntatically wrong. ng-model在语法上是错误的。

  3. square braces [..] refers to the property binding.方括号 [..] 指的是属性绑定。
  4. circle braces (..) refers to the event binding.圆括号 (..) 指的是事件绑定。
  5. when square and circle braces are put together as [(..)] refers two way binding, commonly called banana box.当方括号和圆括号放在一起时,因为 [(..)] 是指双向绑定,通常称为香蕉盒。

So, to fix your error.所以,修复你的错误。

Step 1: Importing FormsModule第 1 步:导入 FormsModule

import {FormsModule} from '@angular/forms'

Step 2: Add it to imports array of your AppModule as第 2 步:将其添加到您的 AppModule 的导入数组中

imports :[ ... , FormsModule ]

Step 3: Change ng-model as ngModel with banana boxes as第 3 步:将ng-model更改为 ngModel,香蕉盒为

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

Note: Also, you can handle the two way databinding separately as well as below注意:此外,您可以分别处理两种方式的数据绑定以及以下

<input id="name" type="text" [ngModel]="name" (ngModelChange)="valueChange($event)"/>

valueChange(value){

}

就我而言,我的输入元素上缺少“名称”属性。

As per Angular2 final, you do not even have to import FORM_DIRECTIVES as suggested above by many.根据 Angular2 final,您甚至FORM_DIRECTIVES像上面许多人建议的那样导入FORM_DIRECTIVES However, the syntax has been changed as kebab-case was dropped for the betterment.但是,随着kebab-case的改进,语法已更改。

Just replace ng-model with ngModel and wrap it in a box of bananas .只需将ng-model替换为ngModel并将其包裹在一盒香蕉中即可 But you have spilt the code into two files now:但是你现在已经把代码分成了两个文件:

app.ts:应用程序:

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

@Component({
  selector: 'ng-app',
  template: `
    <input id="name" type="text" [(ngModel)]="name"  />
    {{ name }}
  `
})
export class DataBindingComponent {
  name: string;

  constructor() {
    this.name = 'Jose';
  }
}

app.module.ts: app.module.ts:

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { DataBindingComponent } from './app'; //app.ts above

@NgModule({
  declarations: [DataBindingComponent],
  imports:      [BrowserModule, FormsModule],
  bootstrap:    [DataBindingComponent]
})
export default class MyAppModule {}

platformBrowserDynamic().bootstrapModule(MyAppModule);

The answer that helped me: The directive [(ngModel)]= not working anymore in rc5帮助我的答案: 指令 [(ngModel)]= 在 rc5 中不再工作

To sum it up: input fields now require property name in the form.总结一下:输入字段现在需要表单中的属性name

In the app.module.ts在 app.module.ts

import { FormsModule } from '@angular/forms';

Later in the @NgModule decorator's import:稍后在 @NgModule 装饰器的导入中:

@NgModule({
imports: [
BrowserModule,
FormsModule
]

})

Angular 2 Beta角 2 测试版

This answer is for those who use Javascript for angularJS v.2.0 Beta.此答案适用于将Javascript用于 angularJS v.2.0 Beta 的人。

To use ngModel in your view you should tell the angular's compiler that you are using a directive called ngModel .要在您的视图中使用ngModel ,您应该告诉 angular 的编译器您正在使用一个名为ngModel的指令。

How?如何?

To use ngModel there are two libraries in angular2 Beta, and they are ng.common.FORM_DIRECTIVES and ng.common.NgModel .要使用ngModel ,angular2 Beta 中有两个库,它们是ng.common.FORM_DIRECTIVESng.common.NgModel

Actually ng.common.FORM_DIRECTIVES is nothing but group of directives which are useful when you are creating a form.实际上ng.common.FORM_DIRECTIVES是一组在创建表单时很有用的指令。 It includes NgModel directive also.它也包括NgModel指令。

app.myApp = ng.core.Component({
    selector: 'my-app',
    templateUrl: 'App/Pages/myApp.html',
    directives: [ng.common.NgModel] // specify all your directives here
}).Class({
    constructor: function () {
        this.myVar = {};
        this.myVar.text = "Testing";
    },

});

Note : To allow the ngModel exists Independently inside reactive form, we have to use ngModelOptions as follows:注意:为了让 ngModel 独立存在于响应式表单中,我们必须使用ngModelOptions如下:

 [ngModelOptions]="{ standalone: true }"

For Example :例如 :

 <mat-form-field appearance="outline" class="w-100">
            <input
              matInput 
              [(ngModel)]="accountType"
              [ngModelOptions]="{ standalone: true }"
            />
 </mat-form-field>

These things are missing/ Wrong:这些东西丢失/错误:

  • Import FormsModule in imports array of module (ngModel requires FormsModule)在模块的导入数组中导入FormsModule (ngModel 需要 FormsModule)
  • ngModel is written as: [(ngModel)]="modelName" ngModel 写成: [(ngModel)]="modelName"

This way, It will work fine!这样,它会正常工作!

instead of ng-model you can use this code:您可以使用以下代码代替 ng-model:

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

@Component({
  selector: 'my-app',
  template: `<input #box (keyup)="0">
    <p>{{box.value}}</p>`,
})
export class AppComponent  {}

inside your app.component.ts在你的 app.component.ts 里面

Add below code to following files.将以下代码添加到以下文件中。

app.component.ts app.component.ts

<input type="text" [(ngModel)]="fname" >
{{fname}}
export class appcomponent {
fname:any;
}

app.module.ts app.module.ts

import {FormsModule} from '@angular/forms';
@NgModule({
imports: [ BrowserModule,FormsModule ],
declarations: [ AppComponent],
bootstrap:    [ AppComponent ]
})

Hope this helps希望这可以帮助

在您的 AppModule 中导入 FormsModule 以使用两种方式绑定 [(ngModel)]

For newer versions of Angular:对于较新版本的 Angular:

  1. -write it as [(ngModel)] = yourSearch - 将其写为[(ngModel)] = yourSearch

  2. declare a empty variable(property) named as yourSearch in .ts file.ts文件中声明一个名为yourSearch的空变量(属性)

  3. add FormsModule in app.module.ts file from - @angular/forms;从 - @angular/forms;app.module.ts文件中添加FormsModule @angular/forms;

  4. if your application is running, then restart it as you made changes in its module.ts file如果您的应用程序正在运行,则在更改其module.ts文件时重新启动它

if you are using lazy loading module, you need to import ngModule and formModule in the current module.如果使用延迟加载模块,则需要在当前模块中导入 ngModule 和 formModule。 example:例子:

//shared.module.ts
import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms'

imports: [
    FormsModule,]

Adding a name property solved the problem for me添加名称属性为我解决了问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM