Angular Material是一个用于构建漂亮的UI组件的库。在使用Angular Material时,我们可以选择使用响应式或模板驱动的方法来实现。
在组件中引入相关模块:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule } from '@angular/forms';
import { MatInputModule, MatButtonModule } from '@angular/material';
@NgModule({
imports: [
CommonModule,
ReactiveFormsModule,
MatInputModule,
MatButtonModule
],
exports: [
CommonModule,
ReactiveFormsModule,
MatInputModule,
MatButtonModule
]
})
export class SharedModule { }
在模板中使用响应式表单控件:
在组件中创建表单组和表单控件:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit {
formGroup: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.formGroup = this.formBuilder.group({
name: ['', Validators.required],
email: ['', [Validators.required, Validators.email]]
});
}
submitForm() {
if (this.formGroup.valid) {
// 处理表单提交逻辑
}
}
}
在模板中使用模板驱动表单控件:
在组件中处理表单提交:
import { Component } from '@angular/core';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.scss']
})
export class FormComponent {
name: string;
email: string;
submitForm() {
if (this.name && this.email) {
// 处理表单提交逻辑
}
}
}
以上是使用Angular Material的响应式和模板驱动方法创建表单的示例。你可以根据自己的需求选择适合的方法来实现。