咨询Angular中FormsModule与ngModel的关联及教程相关问题
Hey there! Let me break down the relationship between FormsModule and ngModel in Angular, and clarify why you hit that issue in the Hero Editor tutorial.
FormsModule is the Home for ngModel First off, [(ngModel)] (the "banana-in-a-box" syntax for two-way data binding) relies on the NgModel directive under the hood. Here's the key point: Angular does not include the NgModel directive in its core set of features. Instead, this directive (along with other template-driven form tools like ngForm, ngModelGroup) is packaged inside the FormsModule from @angular/forms.
In short:
FormsModuleexports theNgModeldirective (and related form utilities)- Without importing
FormsModule, your Angular app has no idea what[(ngModel)]is.
When you added [(ngModel)] to your template but didn’t import FormsModule, Angular threw an error along the lines of:
Can't bind to 'ngModel' since it isn't a known property of 'input'.
This makes sense—Angular’s compiler scans your templates and can’t find a directive that matches ngModel because it wasn’t registered in your module. By adding FormsModule to your AppModule’s imports array, you’re telling Angular: "Hey, load all the directives and services from this module so my components can use them."
Angular’s NgModule system is responsible for organizing and sharing code across your app:
- When you add
FormsModuleto theimportsarray ofAppModule, Angular processes the module and registers all its exported declarations (including theNgModeldirective) with the app’s injector. - Any component declared in
AppModule(like yourHeroesComponentandAppComponent) can now access and use theNgModeldirective in their templates.
Here’s the correct setup example to make it concrete:
// app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; // Import the FormsModule import { AppComponent } from './app.component'; import { HeroesComponent } from './heroes/heroes.component'; @NgModule({ declarations: [ AppComponent, HeroesComponent ], imports: [ BrowserModule, FormsModule // Add it to the imports array ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Once that’s done, you can safely use two-way binding in your component template:
<!-- heroes.component.html --> <input [(ngModel)]="hero.name" placeholder="Enter hero name">
[(ngModel)]depends on theNgModeldirective, which lives inFormsModule- You must import
FormsModuleinto the module where your components are declared to usengModel - The
importsarray inNgModulemakes the module’s exported features available to all components in that module
内容的提问来源于stack exchange,提问作者Freewind

