在Angular中,可以使用嵌套表单来使表单更加具体化和灵活。然而,在数据提交前需要验证表单的有效性,这时候需要使用表单验证。
以下是一个简单的示例,展示了如何使用FormGroup和FormControl构建一个嵌套表单,并对其进行验证。
首先,我们需要从@angular/forms中导入FormGroup和FormControl。
import { FormGroup, FormControl, Validators } from '@angular/forms';
然后,我们可以使用以下代码创建一个嵌套表单:
form: FormGroup = new FormGroup({ firstName: new FormControl('', [Validators.required, Validators.maxLength(20)]), lastName: new FormControl('', [Validators.required, Validators.maxLength(20)]), address: new FormGroup({ street: new FormControl('', [Validators.required]), city: new FormControl('', [Validators.required]), state: new FormControl('', [Validators.required]), zip: new FormControl('', [Validators.required, Validators.pattern(/^\d{5}$/)]) }) });
在这个示例中,我们将嵌套表单作为address字段添加到FormGroup中。我们还为每个表单控件指定了相应的验证规则。
我们可以在模板中使用FormGroup和FormControl的一些方法来检查表单的有效性,比如控件是否被触摸过、控件是否有效,以及表单是否有效等等。
以下是一个简单的示例模板:
在这个模板中,我们绑定了FormGroup和FormControl实例