跳至正文
rdlabo.dev文档

表单

这个入口点针对的是 Angular 22 中的 Signal Forms 模块。

在启动脚本中一次性注册该适配器,然后利用 Angular 的FormField和KitIonicFormField将 Signal Forms 与 Ionic 控件进行绑定。

import { Component, signal } from '@angular/core';
import type { ApplicationConfig } from '@angular/core';
import { FormField, form, required, email, maxLength } from '@angular/forms/signals';
import { IonInput } from '@ionic/angular';
import { KitIonicFormField, provideKitIonicSignalForms } from '@rdlabo/ionic-angular-kit/forms';

export const appConfig: ApplicationConfig = {
  providers: [provideKitIonicSignalForms()],
};

@Component({
  selector: 'app-profile',
  imports: [FormField, KitIonicFormField, IonInput],
  template: `
    <ion-input label="Name" [formField]="profileForm.name"></ion-input>
    <ion-input label="Email" type="email" [formField]="profileForm.email"></ion-input>
  `,
})
export class ProfilePage {
  readonly profile = signal({ name: '', email: '' });
  readonly profileForm = form(this.profile, (path) => {
    required(path.name);
    email(path.email);
    maxLength(path.name, 200);
  });
}

将必填字段留空并移出焦点。Ionic 会显示 errorText,控件将进入 invalid 和 touched 状态。对于 ion-input、ion-textarea、ion-select、ion-checkbox、ion-radio-group 和 ion-toggle,适配器会把第一条非空的显式验证消息复制到 errorText。Angular 验证器未提供消息时,它根据验证错误的 kind 及约束元数据生成通用英文消息,因此内置验证器无需另行配置消息。

对于未知的自定义错误类型,默认消息为 Enter a valid value.。业务规则错误应在字段验证之外处理。为兼容现有行为,显式指定的验证消息仍然优先。如果显式设置 errorText 或绑定 [errorText],适配器不会实例化。

应用可以替换后备错误消息解析器来本地化验证消息,无需修改验证器定义:

import type { ValidationError } from '@angular/forms/signals';
import { KIT_SIGNAL_FORM_ERROR_MESSAGE_RESOLVER } from '@rdlabo/ionic-angular-kit/forms';

export const appConfig: ApplicationConfig = {
  providers: [
    provideKitIonicSignalForms(),
    {
      provide: KIT_SIGNAL_FORM_ERROR_MESSAGE_RESOLVER,
      useValue: (error: ValidationError) => localizedMessageFor(error),
    },
  ],
};

Angular 不会合并通过 provideSignalFormsConfig 注册的多组 CSS 类配置。如果应用提供自己的配置,请在同一个提供者中列出所有需要的 CSS 类映射。

关于匹配的 lint 配置信息,请参考检查您的工具集成情况与 ESLint 的搭配使用。