详解Angular Reactive Form 表单验证(3)

this.signupForm = this.fb.group({ userName: ['', [Validators.required, Validators.minLength(6)]], emailGroup: this.fb.group({ email: ['', [Validators.required, Validators.email]], confirmEmail: ['', [Validators.required]], }, { validator: emailMatcher })

我们通过 formGroupName="groupName" 语法来绑定内嵌的 Form Group。

<div formGroupName="emailGroup" [ngClass]="{'has-error': emailGroup.errors }">

邮箱不匹配的信息是存在 emailGroup 对象的 errors 属性中,而不是存在 confirmEmail 对象的 errors 属性中。

<span *ngIf="!confirmEmail.errors?.required && emailGroup.errors?.match"> 两次输入的邮箱地址不一致 </span>

我有话说

怎么会监听表单值的变化?

Reactive Form

export class AppComponent { constructor(private fb: FormBuilder) { this.form = fb.group({ name: 'semlinker', age: 31 }); this.form.valueChanges.subscribe(data => { console.log('Form changes', data) }); } }

Template-driven Form

模板

<form #myForm="ngForm" (ngSubmit)="onSubmit()"> <input type="text" required [(ngModel)]="user.name"> <input type="number" required [(ngModel)]="user.age"> </form>

组件类

class AppComponent implements AfterViewInit { @ViewChild('myForm') form; ngAfterViewInit() { this.form.control.valueChanges .debounceTime(500) .subscribe(values => this.doSomething(values)); } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wyfzwz.html