
探索角度形式:信号的新替代方案
在 angular 的世界中,无论您是在制作简单的登录页面还是更复杂的用户配置文件界面,表单对于用户交互都是至关重要的。 angular 传统上提供两种主要方法:模板驱动表单和反应式表单。在我之前的 angular 反应式表单系列中,我探索了如何利用反应式表单的强大功能来管理复杂逻辑、创建动态表单以及构建自定义表单控件。
用于管理反应性的新工具 - 信号 - 已在 angular 版本 16 中引入,此后一直是 angular 维护人员关注的焦点,并在版本 17 中变得稳定。信号允许您处理状态更改声明性地,提供了一个令人兴奋的替代方案,将模板驱动表单的简单性与反应表单的强大反应性结合起来。本文将研究信号如何为 angular 中的简单和复杂形式添加反应性。
回顾:角度形式方法
在深入探讨使用信号增强模板驱动表单的主题之前,让我们快速回顾一下 angular 的传统表单方法:
-
模板驱动表单:使用 ngmodel 等指令直接在 html 模板中定义,这些表单易于设置,非常适合简单表单。但是,它们可能无法提供更复杂场景所需的细粒度控制。
这是模板驱动表单的最小示例:
```typescript
import { component } from '@angular/core';
@component({
selector: 'app-root',
templateurl: './app.component.html'
})
export class appcomponent {
name = '';
onsubmit() {
console.log(this.name);
}
}
```
-
反应式表单:使用 angular 的 formgroup、formcontrol 和 formarray 类在组件类中以编程方式进行管理;反应式表单提供对表单状态和验证的精细控制。正如我之前关于 angular reactive forms 的文章所讨论的那样,这种方法非常适合复杂的表单。
这是一个反应式形式的最小示例:
import { component } from '@angular/core'; import { formgroup, formcontrol } from '@angular/forms'; @component({ selector: 'app-root', templateurl: './app.component.html' }) export class appcomponent { form = new formgroup({ name: new formcontrol('') }); onsubmit() { console.log(this.form.value); } }
```html```
引入信号作为处理表单反应性的新方法
随着 angular 16 的发布,信号已经成为管理反应性的新方式。信号提供了一种声明式的状态管理方法,使您的代码更可预测且更易于理解。当应用于表单时,信号可以增强模板驱动表单的简单性,同时提供通常与反应性表单相关的反应性和控制。
让我们探索如何在简单和复杂的形式场景中使用信号。
示例 1:带有信号的简单模板驱动表单
考虑一个基本的登录表单。通常,这将使用模板驱动的表单来实现,如下所示:
// login.component.ts
import { component } from "@angular/core";
@component({
selector: "app-login",
templateurl: "./login.component.html",
})
export class logincomponent {
public email: string = "";
public password: string = "";
onsubmit() {
console.log("form submitted", { email: this.email, password: this.password });
}
}
这种方法适用于简单的表单,但是通过引入信号,我们可以在添加反应功能的同时保持简单性:
// login.component.ts
import { component, computed, signal } from "@angular/core";
import { formsmodule } from "@angular/forms";
@component({
selector: "app-login",
standalone: true,
templateurl: "./login.component.html",
imports: [formsmodule],
})
export class logincomponent {
// define signals for form fields
public email = signal("");
public password = signal(""); // define a computed signal for the form value
public formvalue = computed(() => {
return {
email: this.email(),
password: this.password(),
};
});
public isformvalid = computed(() => {
return this.email().length > 0 && this.password().length > 0;
});
onsubmit() {
console.log("form submitted", this.formvalue());
}
}
在此示例中,表单字段被定义为信号,允许在表单状态发生变化时进行反应式更新。 formvalue 信号提供反映表单当前状态的计算值。这种方法提供了一种更具声明性的方式来管理表单状态和反应性,将模板驱动表单的简单性与信号的强大功能结合起来。
您可能会想将表单直接定义为信号内的对象。虽然这种方法可能看起来更简洁,但在各个字段中输入内容并不会调度反应性更新,这通常会破坏交易。下面是一个 stackblitz 示例,其中一个组件遇到了此类问题:
因此,如果您想对表单字段中的更改做出反应,最好将每个字段定义为单独的信号。通过将每个表单字段定义为单独的信号,您可以确保对各个字段的更改正确触发反应性更新。
示例 2:带有信号的复杂形式
您可能看不到对简单表单(如上面的登录表单)使用信号的好处,但在处理更复杂的表单时它们真正发挥作用。让我们探讨一个更复杂的场景 - 一个用户个人资料表单,其中包含名字、姓氏、电子邮件、电话号码和地址等字段。 phonenumbers 字段是动态的,允许用户根据需要添加或删除电话号码。
以下是如何使用信号定义此形式:
// user-profile.component.ts
import { jsonpipe } from "@angular/common";
import { component, computed, signal } from "@angular/core";
import { formsmodule, validators } from "@angular/forms";
@component({
standalone: true,
selector: "app-user-profile",
templateurl: "./user-profile.component.html",
styleurls: ["./user-profile.component.scss"],
imports: [formsmodule, jsonpipe],
})
export class userprofilecomponent {
public firstname = signal("");
public lastname = signal("");
public email = signal("");
// we need to use a signal for the phone numbers, so we get reactivity when typing in the input fields
public phonenumbers = signal([signal("")]);
public street = signal("");
public city = signal("");
public state = signal("");
public zip = signal("");
public formvalue = computed(() => {
return {
firstname: this.firstname(),
lastname: this.lastname(),
email: this.email(), // we need to do a little mapping here, so we get the actual value for the phone numbers
phonenumbers: this.phonenumbers().map((phonenumber) => phonenumber()),
address: {
street: this.street(),
city: this.city(),
state: this.state(),
zip: this.zip(),
},
};
});
public formvalid = computed(() => {
const { firstname, lastname, email, phonenumbers, address } = this.formvalue(); // regex taken from the angular email validator
const email_regexp = /^(?=.{1,254}$)(?=.{1,64}@)[a-za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-za-z0-9](?:[a-za-z0-9-]{0,61}[a-za-z0-9])?(?:\.[a-za-z0-9](?:[a-za-z0-9-]{0,61}[a-za-z0-9])?)*$/;
const isemailformatvalid = email_regexp.test(email);
return (
firstname.length > 0 &&
lastname.length > 0 &&
email.length > 0 &&
isemailformatvalid &&
phonenumbers.length > 0 && // check if all phone numbers are valid
phonenumbers.every((phonenumber) => phonenumber.length > 0) &&
address.street.length > 0 &&
address.city.length > 0 &&
address.state.length > 0 &&
address.zip.length > 0
);
});
addphonenumber() {
this.phonenumbers.update((phonenumbers) => {
phonenumbers.push(signal(""));
return [...phonenumbers];
});
}
removephonenumber(index: number) {
this.phonenumbers.update((phonenumbers) => {
phonenumbers.splice(index, 1);
return [...phonenumbers];
});
}
}
请注意,phonenumbers 字段被定义为信号数组中的一个信号。这种结构使我们能够跟踪各个电话号码的更改并反应性地更新表单状态。 addphonenumber 和removephonenumber 方法更新phonenumbers 信号数组,触发表单中的反应性更新。










