Ngx-Formly 使用教程
项目介绍
Ngx-Formly 是一个用于 Angular 的动态(JSON 驱动)表单库,它为你的应用程序表单带来了无与伦比的维护性。Ngx-Formly 的主要特点包括自动表单生成、易于扩展的自定义字段类型和验证、支持多种模式(如 Formly Schema 和 JSON Schema)、以及多种内置主题。
项目快速启动
安装
首先,你需要安装 ngx-formly
及其相关 UI 库,例如 @ngx-formly/bootstrap
:
npm install @ngx-formly/core @ngx-formly/bootstrap
配置
在你的 Angular 项目中,导入 FormlyModule 并在 AppModule
中进行配置:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { FormlyModule } from '@ngx-formly/core';
import { FormlyBootstrapModule } from '@ngx-formly/bootstrap';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
ReactiveFormsModule,
FormlyModule.forRoot(),
FormlyBootstrapModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
使用
在你的组件中使用 Formly 来生成表单:
import { Component } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { FormlyFieldConfig } from '@ngx-formly/core';
@Component({
selector: 'app-root',
template: `
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<formly-form [form]="form" [fields]="fields" [model]="model"></formly-form>
<button type="submit" class="btn btn-default">Submit</button>
</form>
`,
})
export class AppComponent {
form = new FormGroup({});
model = {};
fields: FormlyFieldConfig[] = [
{
key: 'email',
type: 'input',
templateOptions: {
type: 'email',
label: 'Email address',
placeholder: 'Enter email',
required: true,
}
},
{
key: 'password',
type: 'input',
templateOptions: {
type: 'password',
label: 'Password',
placeholder: 'Password',
required: true,
}
}
];
onSubmit() {
if (this.form.valid) {
console.log(this.model);
}
}
}
应用案例和最佳实践
自定义字段类型
你可以通过扩展 FormlyFieldConfig
来创建自定义字段类型。例如,创建一个自定义的日期选择器字段:
import { FormlyFieldConfig } from '@ngx-formly/core';
export function datePickerField(): FormlyFieldConfig {
return {
type: 'datepicker',
templateOptions: {
label: 'Date',
placeholder: 'Select a date',
required: true,
},
wrappers: ['form-field'],
};
}
表单验证
Formly 支持自定义验证和内置验证。例如,添加一个自定义的电子邮件验证:
import { FormlyFieldConfig } from '@ngx-formly/core';
export function emailValidator(control: FormControl): ValidationErrors {
return Validators.email(control) ? { 'email': true } : null;
}
export function emailValidatorMessage(err, field: FormlyFieldConfig) {
return `"${field.templateOptions.label}" is not a valid email address`;
}
典型生态项目
集成 Material Design
Formly 支持多种 UI 库,包括 Angular Material。你可以通过安装 @ngx-formly/material
来