angular-forms

angular-forms

热门

使用 Angular v21+ 中新的 Signal Forms API 构建基于信号的表单。适用于表单创建,支持自动双向绑定、基于模式的验证、字段状态管理和动态表单。在实现表单、添加验证、创建多步骤表单或构建带有条件字段的表单时触发。Signal Forms 是实验性的,但推荐用于新的 Angular 项目。不要用于不使用信号的模板驱动表单或第三方表单库(如 Formly 或 ngx-formly)。

596Star
70Fork
更新于 2026/3/23
SKILL.md
readonly只读
name
angular-forms
description

使用 Angular v21+ 中新的 Signal Forms API 构建基于信号的表单。适用于表单创建,支持自动双向绑定、基于模式的验证、字段状态管理和动态表单。在实现表单、添加验证、创建多步骤表单或构建带有条件字段的表单时触发。Signal Forms 是实验性的,但推荐用于新的 Angular 项目。不要用于不使用信号的模板驱动表单或第三方表单库(如 Formly 或 ngx-formly)。

Angular Signal Forms

使用 Angular 的 Signal Forms API 构建类型安全、响应式的表单。Signal Forms 提供自动双向绑定、基于模式的验证和响应式字段状态。

注意: Signal Forms 在 Angular v21 中是实验性的。对于需要稳定性的生产应用,请参阅 references/form-patterns.md 了解 Reactive Forms 模式。

基本设置

import { Component, signal } from '@angular/core';
import { form, FormField, required, email } from '@angular/forms/signals';

interface LoginData {
  email: string;
  password: string;
}

@Component({
  selector: 'app-login',
  imports: [FormField],
  template: `
    <form (submit)="onSubmit($event)">
      <label>
        Email
        <input type="email" [formField]="loginForm.email" />
      </label>
      @if (loginForm.email().touched() && loginForm.email().invalid()) {
        <p class="error">{{ loginForm.email().errors()[0].message }}</p>
      }
      
      <label>
        Password
        <input type="password" [formField]="loginForm.password" />
      </label>
      @if (loginForm.password().touched() && loginForm.password().invalid()) {
        <p class="error">{{ loginForm.password().errors()[0].message }}</p>
      }
      
      <button type="submit" [disabled]="loginForm().invalid()">Login</button>
    </form>
  `,
})
export class Login {
  // 表单模型 - 一个可写信号
  loginModel = signal<LoginData>({
    email: '',
    password: '',
  });
  
  // 创建带有验证模式的表单
  loginForm = form(this.loginModel, (schemaPath) => {
    required(schemaPath.email, { message: 'Email is required' });
    email(schemaPath.email, { message: 'Enter a valid email address' });
    required(schemaPath.password, { message: 'Password is required' });
  });
  
  onSubmit(event: Event) {
    event.preventDefault();
    if (this.loginForm().valid()) {
      const credentials = this.loginModel();
      console.log('Submitting:', credentials);
    }
  }
}

表单模型

表单模型是可写信号,作为单一数据源:

// 定义接口以实现类型安全
interface UserProfile {
  name: string;
  email: string;
  age: number | null;
  preferences: {
    newsletter: boolean;
    theme: 'light' | 'dark';
  };
}

// 创建带有初始值的模型信号
const userModel = signal<UserProfile>({
  name: '',
  email: '',
  age: null,
  preferences: {
    newsletter: false,
    theme: 'light',
  },
});

// 从模型创建表单
const userForm = form(userModel);

// 通过点符号访问嵌套字段
userForm.name                    // FieldTree<string>
userForm.preferences.theme       // FieldTree<'light' | 'dark'>

读取值

// 读取整个模型
const data = this.userModel();

// 通过字段状态读取字段值
const name = this.userForm.name().value();
const theme = this.userForm.preferences.theme().value();

更新值

// 替换整个模型
this.userModel.set({
  name: 'Alice',
  email: 'alice@example.com',
  age: 30,
  preferences: { newsletter: true, theme: 'dark' },
});

// 更新单个字段
this.userForm.name().value.set('Bob');
this.userForm.age().value.update(age => (age ?? 0) + 1);

字段状态

每个字段提供用于验证、交互和可用性的响应式信号:

const emailField = this.form.email();

// 验证状态
emailField.valid()      // 如果通过所有验证则为 true
emailField.invalid()    // 如果有验证错误则为 true
emailField.errors()     // 错误对象数组
emailField.pending()    // 如果异步验证正在进行则为 true

// 交互状态
emailField.touched()    // 聚焦并失焦后为 true
emailField.dirty()      // 用户修改后为 true

// 可用性状态
emailField.disabled()   // 如果字段被禁用则为 true
emailField.hidden()     // 如果字段应隐藏则为 true
emailField.readonly()   // 如果字段为只读则为 true

// 值
emailField.value()      // 当前字段值(信号)

表单级状态

表单本身也是一个字段,具有聚合状态:

// 当所有交互字段都有效时,表单有效
this.form().valid()

// 当任何字段被触摸时,表单被触摸
this.form().touched()

// 当任何字段被修改时,表单变脏
this.form().dirty()

验证

内置验证器

import { 
  form, required, email, min, max, 
  minLength, maxLength, pattern 
} from '@angular/forms/signals';

const userForm = form(this.userModel, (schemaPath) => {
  // 必填字段
  required(schemaPath.name, { message: 'Name is required' });
  
  // 邮箱格式
  email(schemaPath.email, { message: 'Invalid email' });
  
  // 数值范围
  min(schemaPath.age, 18, { message: 'Must be 18+' });
  max(schemaPath.age, 120, { message: 'Invalid age' });
  
  // 字符串/数组长度
  minLength(schemaPath.password, 8, { message: 'Min 8 characters' });
  maxLength(schemaPath.bio, 500, { message: 'Max 500 characters' });
  
  // 正则表达式模式
  pattern(schemaPath.phone, /^\d{3}-\d{3}-\d{4}$/, {
    message: 'Format: 555-123-4567',
  });
});

条件验证

const orderForm = form(this.orderModel, (schemaPath) => {
  required(schemaPath.promoCode, {
    message: 'Promo code required for discounts',
    when: ({ valueOf }) => valueOf(schemaPath.applyDiscount),
  });
});

自定义验证器

import { validate } from '@angular/forms/signals';

const signupForm = form(this.signupModel, (schemaPath) => {
  // 自定义验证逻辑
  validate(schemaPath.username, ({ value }) => {
    if (value().includes(' ')) {
      return { kind: 'noSpaces', message: 'Username cannot contain spaces' };
    }
    return null;
  });
});

跨字段验证

const passwordForm = form(this.passwordModel, (schemaPath) => {
  required(schemaPath.password);
  required(schemaPath.confirmPassword);
  
  // 比较字段
  validate(schemaPath.confirmPassword, ({ value, valueOf }) => {
    if (value() !== valueOf(schemaPath.password)) {
      return { kind: 'mismatch', message: 'Passwords do not match' };
    }
    return null;
  });
});

异步验证

import { validateHttp } from '@angular/forms/signals';

const signupForm = form(this.signupModel, (schemaPath) => {
  validateHttp(schemaPath.username, {
    request: ({ value }) => `/api/check-username?u=${value()}`,
    onSuccess: (response: { taken: boolean }) => {
      if (response.taken) {
        return { kind: 'taken', message: 'Username already taken' };
      }
      return null;
    },
    onError: () => ({
      kind: 'networkError',
      message: 'Could not verify username',
    }),
  });
});

条件字段

隐藏字段

import { hidden } from '@angular/forms/signals';

const profileForm = form(this.profileModel, (schemaPath) => {
  hidden(schemaPath.publicUrl, ({ valueOf }) => !valueOf(schemaPath.isPublic));
});
@if (!profileForm.publicUrl().hidden()) {
  <input [formField]="profileForm.publicUrl" />
}

禁用字段

import { disabled } from '@angular/forms/signals';

const orderForm = form(this.orderModel, (schemaPath) => {
  disabled(schemaPath.couponCode, ({ valueOf }) => valueOf(schemaPath.total) < 50);
});

只读字段

import { readonly } from '@angular/forms/signals';

const accountForm = form(this.accountModel, (schemaPath) => {
  readonly(schemaPath.username); // 始终只读
});

表单提交

import { submit } from '@angular/forms/signals';

@Component({
  template: `
    <form (submit)="onSubmit($event)">
      <input [formField]="form.email" />
      <input [formField]="form.password" />
      <button type="submit" [disabled]="form().invalid()">Submit</button>
    </form>
  `,
})
export class Login {
  model = signal({ email: '', password: '' });
  form = form(this.model, (schemaPath) => {
    required(schemaPath.email);
    required(schemaPath.password);
  });
  
  onSubmit(event: Event) {
    event.preventDefault();
    
    // submit() 标记所有字段为已触摸,并在有效时运行回调
    submit(this.form, async () => {
      await this.authService.login(this.model());
    });
  }
}

数组和动态字段

interface Order {
  items: Array<{ product: string; quantity: number }>;
}

@Component({
  template: `
    @for (item of orderForm.items; track $index; let i = $index) {
      <div>
        <input [formField]="item.product" placeholder="Product" />
        <input [formField]="item.quantity" type="number" />
        <button type="button" (click)="removeItem(i)">Remove</button>
      </div>
    }
    <button type="button" (click)="addItem()">Add Item</button>
  `,
})
export class Order {
  orderModel = signal<Order>({
    items: [{ product: '', quantity: 1 }],
  });
  
  orderForm = form(this.orderModel, (schemaPath) => {
    applyEach(schemaPath.items, (item) => {
      required(item.product, { message: 'Product required' });
      min(item.quantity, 1, { message: 'Min quantity is 1' });
    });
  });
  
  addItem() {
    this.orderModel.update(m => ({
      ...m,
      items: [...m.items, { product: '', quantity: 1 }],
    }));
  }
  
  removeItem(index: number) {
    this.orderModel.update(m => ({
      ...m,
      items: m.items.filter((_, i) => i !== index),
    }));
  }
}

显示错误

<input [formField]="form.email" />

@if (form.email().touched() && form.email().invalid()) {
  <ul class="errors">
    @for (error of form.email().errors(); track error) {
      <li>{{ error.message }}</li>
    }
  </ul>
}

@if (form.email().pending()) {
  <span>Validating...</span>
}

基于状态的样式

<input
  [formField]="form.email"
  [class.is-invalid]="form.email().touched() && form.email().invalid()"
  [class.is-valid]="form.email().touched() && form.email().valid()"
/>

重置表单

async onSubmit() {
  if (!this.form().valid()) return;
  
  await this.api.submit(this.model());
  
  // 清除交互状态
  this.form().reset();
  
  // 清除值
  this.model.set({ email: '', password: '' });
}

有关 Reactive Forms 模式(生产稳定),请参阅 references/form-patterns.md