4 回答

TA貢獻1909條經驗 獲得超7個贊
Angular已于9月15日發布了最終版本。與Angular 1不同,您可以ngModel在Angular 2中使用指令進行兩種方式的數據綁定,但是您需要以一些不同的方式來編寫它,例如[(ngModel)](Banana in a box語法)。現在幾乎所有的angular2核心指令都不支持,kebab-case而應該使用camelCase。
現在ngModel指令屬于FormsModule,這就是為什么您應該import在(NgModule)的元數據選項中使用FormsModulefrom @angular/forms模塊。之后,您可以在頁面內使用指令。importsAppModulengModel
app / 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
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
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);

TA貢獻1719條經驗 獲得超6個贊
關鍵點:
僅當FormsModule作為AppModule的一部分可用時,angular2中的ngModel才有效。
ng-model 在語法上是錯誤的。
方括號[..]表示屬性綁定。
圓括號(..)表示事件綁定。
當方括號和圓括號放在一起時,[[..]]表示雙向綁定,通常稱為香蕉盒。
因此,修復您的錯誤。
步驟1:導入FormsModule
import {FormsModule} from '@angular/forms'
第2步:將其添加到AppModule的import數組中,作為
imports :[ ... , FormsModule ]
步驟3:ng-model將香蕉盒更改為ngModel
<input id="name" type="text" [(ngModel)]="name" />
注意:此外,您也可以分別處理以下兩種方式的數據綁定
<input id="name" type="text" [ngModel]="name" (ngModelChange)="valueChange($event)"/>
valueChange(value){
}
- 4 回答
- 0 關注
- 524 瀏覽
添加回答
舉報