📜  ngmodel 组件 angular - Javascript (1)

📅  最后修改于: 2023-12-03 15:03:10.904000             🧑  作者: Mango

NgModel Component in Angular

NgModel is a built-in Angular directive that simplifies the two-way data binding between form controls and model properties. It is a part of the FormsModule, which is required to use NgModel in an Angular application.

How to Use NgModel

To use NgModel, you’ll need to first import the FormsModule in your Angular module. You can do this by adding FormsModule to the imports array of the module decorator:

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

import { AppComponent } from './app.component';

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

Once FormsModule is imported, you can use NgModel directive in your templates to bind data to form controls. Here’s an example:

<input [(ngModel)]="firstName" />

In this example, we’re binding the value of the firstName property to the input field using NgModel.

Two-Way Data Binding with NgModel

NgModel enables two-way data binding between form controls and model properties. When the user types into an input field, the value of the model property is updated, and vice versa.

Here’s an example:

<input [(ngModel)]="firstName" />
<p>Hello, {{firstName}}!</p>

In this example, we’re binding the value of the firstName property to the input field using NgModel. We’re also displaying the value of the firstName property in a paragraph element using string interpolation.

Whenever the user types into the input field, the value of the firstName property is updated, and the paragraph element is updated to reflect the new value.

Conclusion

NgModel is a powerful Angular directive that simplifies the two-way data binding between form controls and model properties. It’s easy to use and enables rapid development of Angular applications.