创建一个表单的模板,可以在其中定义各种表单元素,如文本框、下拉框、复选框等。
通过在组件中定义表单数据模型,可以在表单中收集用户输入的数据。如下:
import { Component } from '@angular/core';
@Component({
selector: 'app-contact-form',
templateUrl: './contact-form.component.html'
})
export class ContactFormComponent {
model = new ContactForm();
}
export class ContactForm {
name: string;
email: string;
subject: string;
message: string;
}
为了在模板中使用表单指令,需要在应用程序中导入FormsModule。
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { ContactFormComponent } from './contact-form/contact-form.component';
@NgModule({
declarations: [
AppComponent,
ContactFormComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
在模板中使用ngModel指令将表单元素