响应式表单 - 将字段标记为已触摸
Reactive Forms - mark fields as touched
我无法找到如何将所有表单字段标记为已触摸。
主要问题是,如果我不触摸字段并尝试提交表单 - 验证错误不会显示出来。我的控制器中有这段代码的占位符。
我的想法很简单:
- 用户点击提交按钮
- 所有字段都标记为已触摸
- 错误格式化程序重新运行并显示验证错误
如果有人有其他想法如何在提交时显示错误,而不实施新方法 - 请分享。谢谢!
我的简化形式:
<form class="form-horizontal" [formGroup]="form" (ngSubmit)="onSubmit(form.value)">
<input type="text" id="title" class="form-control" formControlName="title">
<span class="help-block" *ngIf="formErrors.title">{{ formErrors.title }}</span>
<button>Submit</button>
</form>
我的控制器:
import {Component, OnInit} from '@angular/core';
import {FormGroup, FormBuilder, Validators} from '@angular/forms';
@Component({
selector : 'pastebin-root',
templateUrl: './app.component.html',
styleUrls : ['./app.component.css']
})
export class AppComponent implements OnInit {
form: FormGroup;
formErrors = {
'title': ''
};
validationMessages = {
'title': {
'required': 'Title is required.'
}
};
constructor(private fb: FormBuilder) {
}
ngOnInit(): void {
this.buildForm();
}
onSubmit(form: any): void {
// somehow touch all elements so onValueChanged will generate correct error messages
this.onValueChanged();
if (this.form.valid) {
console.log(form);
}
}
buildForm(): void {
this.form = this.fb.group({
'title': ['', Validators.required]
});
this.form.valueChanges
.subscribe(data => this.onValueChanged(data));
}
onValueChanged(data?: any) {
if (!this.form) {
return;
}
const form = this.form;
for (const field in this.formErrors) {
if (!this.formErrors.hasOwnProperty(field)) {
continue;
}
// clear previous error message (if any)
this.formErrors[field] = '';
const control = form.get(field);
if (control && control.touched && !control.valid) {
const messages = this.validationMessages[field];
for (const key in control.errors) {
if (!control.errors.hasOwnProperty(key)) {
continue;
}
this.formErrors[field] += messages[key] + ' ';
}
}
}
}
}
onSubmit(form: any): void {
if (!this.form) {
this.form.markAsTouched();
// this.form.markAsDirty(); <-- this can be useful
}
}
这是我的做法。我不希望在按下提交按钮(或触摸表单)之前显示错误字段。
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {OnInit} from "@angular/core";
export class MyFormComponent implements OnInit {
doValidation = false;
form: FormGroup;
constructor(fb: FormBuilder) {
this.form = fb.group({
title: ["", Validators.required]
});
}
ngOnInit() {
}
clickSubmitForm() {
this.doValidation = true;
if (this.form.valid) {
console.log(this.form.value);
};
}
}
<form class="form-horizontal" [formGroup]="form" >
<input type="text" class="form-control" formControlName="title">
<div *ngIf="form.get('title').hasError('required') && doValidation" class="alert alert-danger">
title is required
</div>
<button (click)="clickSubmitForm()">Submit</button>
</form>
以下函数递归遍历窗体组中的控件并轻轻触摸它们。因为控件的字段是一个对象,所以代码在窗体组的控件字段上调用 Object.values()
。
/**
* Marks all controls in a form group as touched
* @param formGroup - The form group to touch
*/
private markFormGroupTouched(formGroup: FormGroup) {
(<any>Object).values(formGroup.controls).forEach(control => {
control.markAsTouched();
if (control.controls) {
this.markFormGroupTouched(control);
}
});
}
我完全理解 OP 的挫败感。我使用以下内容:
效用函数:
/**
* Determines if the given form is valid by touching its controls
* and updating their validity.
* @param formGroup the container of the controls to be checked
* @returns {boolean} whether or not the form was invalid.
*/
export function formValid(formGroup: FormGroup): boolean {
return !Object.keys(formGroup.controls)
.map(controlName => formGroup.controls[controlName])
.filter(control => {
control.markAsTouched();
control.updateValueAndValidity();
return !control.valid;
}).length;
}
用法:
onSubmit() {
if (!formValid(this.formGroup)) {
return;
}
// ... TODO: logic if form is valid.
}
请注意,此函数尚不支持嵌套控件。
我遇到了这个问题,但找到了 "correct" 方法,尽管它没有出现在我找到的任何 Angular 教程中。
在您的 HTML 中,在 form
标记上,添加与 Template-Driven 表单示例相同的模板引用变量 #myVariable='ngForm'
('hashtag' 变量)使用,除了 Reactive Forms 示例使用的内容:
<form [formGroup]="myFormGroup" #myForm="ngForm" (ngSubmit)="submit()">
现在您可以访问模板中的 myForm.submitted
,您可以使用它来代替(或补充)myFormGroup.controls.X.touched
:
<div *ngIf="myForm.submitted" class="text-error">
<span *ngIf="myFormGroup.controls.myFieldX.errors?.badDate">invalid date format</span>
<span *ngIf="myFormGroup.controls.myFieldX.errors?.isPastDate">date cannot be in the past.</span>
</div>
知道 myForm.form === myFormGroup
是正确的...只要您不要忘记 ="ngForm"
部分。如果单独使用 #myForm
,它将不起作用,因为 var 将设置为 HtmlElement 而不是驱动该元素的指令。
知道 myFormGroup
根据 Reactive Forms 教程在您的组件的打字稿代码中可见,但 myForm
不可见,除非您通过方法调用传递它,例如 submit(myForm)
到 submit(myForm: NgForm): void {...}
。 (注意 NgForm
在打字稿中是标题大写,但在 HTML 中是驼峰式大小写。)
这是我的解决方案
static markFormGroupTouched (FormControls: { [key: string]: AbstractControl } | AbstractControl[]): void {
const markFormGroupTouchedRecursive = (controls: { [key: string]: AbstractControl } | AbstractControl[]): void => {
_.forOwn(controls, (c, controlKey) => {
if (c instanceof FormGroup || c instanceof FormArray) {
markFormGroupTouchedRecursive(c.controls);
} else {
c.markAsTouched();
}
});
};
markFormGroupTouchedRecursive(FormControls);
}
我 运行 遇到了同样的问题,但我不想 "pollute" 我的组件包含处理此问题的代码。特别是因为我需要以多种形式使用它并且我不想在各种场合重复代码。
因此我创建了一个指令(使用目前发布的答案)。该指令装饰了 NgForm 的 onSubmit
-Method:如果表单无效,它会将所有字段标记为已触及并中止提交。否则通常的 onSubmit-Method 会正常执行。
import {Directive, Host} from '@angular/core';
import {NgForm} from '@angular/forms';
@Directive({
selector: '[appValidateOnSubmit]'
})
export class ValidateOnSubmitDirective {
constructor(@Host() form: NgForm) {
const oldSubmit = form.onSubmit;
form.onSubmit = function (): boolean {
if (form.invalid) {
const controls = form.controls;
Object.keys(controls).forEach(controlName => controls[controlName].markAsTouched());
return false;
}
return oldSubmit.apply(form, arguments);
};
}
}
用法:
<form (ngSubmit)="submit()" appValidateOnSubmit>
<!-- ... form controls ... -->
</form>
这是我实际使用的代码。
validateAllFormFields(formGroup: any) {
// This code also works in IE 11
Object.keys(formGroup.controls).forEach(field => {
const control = formGroup.get(field);
if (control instanceof FormControl) {
control.markAsTouched({ onlySelf: true });
} else if (control instanceof FormGroup) {
this.validateAllFormFields(control);
} else if (control instanceof FormArray) {
this.validateAllFormFields(control);
}
});
}
遍历表单控件并将它们标记为已触摸也可行:
for(let i in this.form.controls)
this.form.controls[i].markAsTouched();
此代码适用于我:
markAsRequired(formGroup: FormGroup) {
if (Reflect.getOwnPropertyDescriptor(formGroup, 'controls')) {
(<any>Object).values(formGroup.controls).forEach(control => {
if (control instanceof FormGroup) {
// FormGroup
markAsRequired(control);
}
// FormControl
control.markAsTouched();
});
}
}
关于@masterwork 的回答。
我尝试了该解决方案,但是当函数尝试递归地挖掘 FormGroup 内部时出现错误,因为在这一行传递了 FormControl 参数而不是 FormGroup:
control.controls.forEach(c => this.markFormGroupTouched(c));
这是我的解决方案
markFormGroupTouched(formGroup: FormGroup) {
(<any>Object).values(formGroup.controls).forEach(control => {
if (control.controls) { // control is a FormGroup
markFormGroupTouched(control);
} else { // control is a FormControl
control.markAsTouched();
}
});
}
无需递归的解决方案
对于那些担心性能的人,我想出了一个不使用递归的解决方案,尽管它仍然迭代所有级别的所有控件。
/**
* Iterates over a FormGroup or FormArray and mark all controls as
* touched, including its children.
*
* @param {(FormGroup | FormArray)} rootControl - Root form
* group or form array
* @param {boolean} [visitChildren=true] - Specify whether it should
* iterate over nested controls
*/
public markControlsAsTouched(rootControl: FormGroup | FormArray,
visitChildren: boolean = true) {
let stack: (FormGroup | FormArray)[] = [];
// Stack the root FormGroup or FormArray
if (rootControl &&
(rootControl instanceof FormGroup || rootControl instanceof FormArray)) {
stack.push(rootControl);
}
while (stack.length > 0) {
let currentControl = stack.pop();
(<any>Object).values(currentControl.controls).forEach((control) => {
// If there are nested forms or formArrays, stack them to visit later
if (visitChildren &&
(control instanceof FormGroup || control instanceof FormArray)
) {
stack.push(control);
} else {
control.markAsTouched();
}
});
}
}
此解决方案适用于 FormGroup 和 FormArray。
您可以在这里尝试一下:angular-mark-as-touched
参见this gem。
迄今为止我见过的最优雅的解决方案。
完整代码
import { Injectable } from '@angular/core';
import { FormGroup } from '@angular/forms';
const TOUCHED = 'markAsTouched';
const UNTOUCHED = 'markAsUntouched';
const DIRTY = 'markAsDirty';
const PENDING = 'markAsPending';
const PRISTINE = 'markAsPristine';
const FORM_CONTROL_STATES: Array<string> = [TOUCHED, UNTOUCHED, DIRTY, PENDING, PRISTINE];
@Injectable({
providedIn: 'root'
})
export class FormStateService {
markAs (form: FormGroup, state: string): FormGroup {
if (FORM_CONTROL_STATES.indexOf(state) === -1) {
return form;
}
const controls: Array<string> = Object.keys(form.controls);
for (const control of controls) {
form.controls[control][state]();
}
return form;
}
markAsTouched (form: FormGroup): FormGroup {
return this.markAs(form, TOUCHED);
}
markAsUntouched (form: FormGroup): FormGroup {
return this.markAs(form, UNTOUCHED);
}
markAsDirty (form: FormGroup): FormGroup {
return this.markAs(form, DIRTY);
}
markAsPending (form: FormGroup): FormGroup {
return this.markAs(form, PENDING);
}
markAsPristine (form: FormGroup): FormGroup {
return this.markAs(form, PRISTINE);
}
}
从Angular 8你可以简单地使用
this.form.markAllAsTouched();
将控件及其子控件标记为已触摸。
从 Angular v8 开始,您在 markAllAsTouched
方法的帮助下得到了这个 built-in。
举个例子,你可以这样使用它
form.markAllAsTouched();
查看官方文档:https://angular.io/api/forms/AbstractControl#markallastouched
/**
* Marks as a touched
* @param { FormGroup } formGroup
*
* @return {void}
*/
markFormGroupTouched(formGroup: FormGroup) {
Object.values(formGroup.controls).forEach((control: any) => {
if (control instanceof FormControl) {
control.markAsTouched();
control.updateValueAndValidity();
} else if (control instanceof FormGroup) {
this.markFormGroupTouched(control);
}
});
}
查看:
<button (click)="Submit(yourFormGroup)">Submit</button>
API
Submit(form: any) {
if (form.status === 'INVALID') {
for (let inner in details.controls) {
details.get(inner).markAsTouched();
}
return false;
}
// as it return false it breaks js execution and return
我制作了一个版本,对所呈现的答案进行了一些改动,对于那些使用旧版本8的angular,我想分享给那些有用的人。
效用函数:
import {FormControl, FormGroup} from "@angular/forms";
function getAllControls(formGroup: FormGroup): FormControl[] {
const controls: FormControl[] = [];
(<any>Object).values(formGroup.controls).forEach(control => {
if (control.controls) { // control is a FormGroup
const allControls = getAllControls(control);
controls.push(...allControls);
} else { // control is a FormControl
controls.push(control);
}
});
return controls;
}
export function isValidForm(formGroup: FormGroup): boolean {
return getAllControls(formGroup)
.filter(control => {
control.markAsTouched();
return !control.valid;
}).length === 0;
}
用法:
onSubmit() {
if (this.isValidForm()) {
// ... TODO: logic if form is valid
}
}
根据@masterwork
angular 版本 8
的打字稿代码
private markFormGroupTouched(formGroup: FormGroup) {
(Object as any).values(formGroup.controls).forEach(control => {
control.markAsTouched();
if (control.controls) {
this.markFormGroupTouched(control);
}
}); }
我无法找到如何将所有表单字段标记为已触摸。
主要问题是,如果我不触摸字段并尝试提交表单 - 验证错误不会显示出来。我的控制器中有这段代码的占位符。
我的想法很简单:
- 用户点击提交按钮
- 所有字段都标记为已触摸
- 错误格式化程序重新运行并显示验证错误
如果有人有其他想法如何在提交时显示错误,而不实施新方法 - 请分享。谢谢!
我的简化形式:
<form class="form-horizontal" [formGroup]="form" (ngSubmit)="onSubmit(form.value)">
<input type="text" id="title" class="form-control" formControlName="title">
<span class="help-block" *ngIf="formErrors.title">{{ formErrors.title }}</span>
<button>Submit</button>
</form>
我的控制器:
import {Component, OnInit} from '@angular/core';
import {FormGroup, FormBuilder, Validators} from '@angular/forms';
@Component({
selector : 'pastebin-root',
templateUrl: './app.component.html',
styleUrls : ['./app.component.css']
})
export class AppComponent implements OnInit {
form: FormGroup;
formErrors = {
'title': ''
};
validationMessages = {
'title': {
'required': 'Title is required.'
}
};
constructor(private fb: FormBuilder) {
}
ngOnInit(): void {
this.buildForm();
}
onSubmit(form: any): void {
// somehow touch all elements so onValueChanged will generate correct error messages
this.onValueChanged();
if (this.form.valid) {
console.log(form);
}
}
buildForm(): void {
this.form = this.fb.group({
'title': ['', Validators.required]
});
this.form.valueChanges
.subscribe(data => this.onValueChanged(data));
}
onValueChanged(data?: any) {
if (!this.form) {
return;
}
const form = this.form;
for (const field in this.formErrors) {
if (!this.formErrors.hasOwnProperty(field)) {
continue;
}
// clear previous error message (if any)
this.formErrors[field] = '';
const control = form.get(field);
if (control && control.touched && !control.valid) {
const messages = this.validationMessages[field];
for (const key in control.errors) {
if (!control.errors.hasOwnProperty(key)) {
continue;
}
this.formErrors[field] += messages[key] + ' ';
}
}
}
}
}
onSubmit(form: any): void {
if (!this.form) {
this.form.markAsTouched();
// this.form.markAsDirty(); <-- this can be useful
}
}
这是我的做法。我不希望在按下提交按钮(或触摸表单)之前显示错误字段。
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {OnInit} from "@angular/core";
export class MyFormComponent implements OnInit {
doValidation = false;
form: FormGroup;
constructor(fb: FormBuilder) {
this.form = fb.group({
title: ["", Validators.required]
});
}
ngOnInit() {
}
clickSubmitForm() {
this.doValidation = true;
if (this.form.valid) {
console.log(this.form.value);
};
}
}
<form class="form-horizontal" [formGroup]="form" >
<input type="text" class="form-control" formControlName="title">
<div *ngIf="form.get('title').hasError('required') && doValidation" class="alert alert-danger">
title is required
</div>
<button (click)="clickSubmitForm()">Submit</button>
</form>
以下函数递归遍历窗体组中的控件并轻轻触摸它们。因为控件的字段是一个对象,所以代码在窗体组的控件字段上调用 Object.values()
。
/**
* Marks all controls in a form group as touched
* @param formGroup - The form group to touch
*/
private markFormGroupTouched(formGroup: FormGroup) {
(<any>Object).values(formGroup.controls).forEach(control => {
control.markAsTouched();
if (control.controls) {
this.markFormGroupTouched(control);
}
});
}
我完全理解 OP 的挫败感。我使用以下内容:
效用函数:
/**
* Determines if the given form is valid by touching its controls
* and updating their validity.
* @param formGroup the container of the controls to be checked
* @returns {boolean} whether or not the form was invalid.
*/
export function formValid(formGroup: FormGroup): boolean {
return !Object.keys(formGroup.controls)
.map(controlName => formGroup.controls[controlName])
.filter(control => {
control.markAsTouched();
control.updateValueAndValidity();
return !control.valid;
}).length;
}
用法:
onSubmit() {
if (!formValid(this.formGroup)) {
return;
}
// ... TODO: logic if form is valid.
}
请注意,此函数尚不支持嵌套控件。
我遇到了这个问题,但找到了 "correct" 方法,尽管它没有出现在我找到的任何 Angular 教程中。
在您的 HTML 中,在 form
标记上,添加与 Template-Driven 表单示例相同的模板引用变量 #myVariable='ngForm'
('hashtag' 变量)使用,除了 Reactive Forms 示例使用的内容:
<form [formGroup]="myFormGroup" #myForm="ngForm" (ngSubmit)="submit()">
现在您可以访问模板中的 myForm.submitted
,您可以使用它来代替(或补充)myFormGroup.controls.X.touched
:
<div *ngIf="myForm.submitted" class="text-error">
<span *ngIf="myFormGroup.controls.myFieldX.errors?.badDate">invalid date format</span>
<span *ngIf="myFormGroup.controls.myFieldX.errors?.isPastDate">date cannot be in the past.</span>
</div>
知道 myForm.form === myFormGroup
是正确的...只要您不要忘记 ="ngForm"
部分。如果单独使用 #myForm
,它将不起作用,因为 var 将设置为 HtmlElement 而不是驱动该元素的指令。
知道 myFormGroup
根据 Reactive Forms 教程在您的组件的打字稿代码中可见,但 myForm
不可见,除非您通过方法调用传递它,例如 submit(myForm)
到 submit(myForm: NgForm): void {...}
。 (注意 NgForm
在打字稿中是标题大写,但在 HTML 中是驼峰式大小写。)
这是我的解决方案
static markFormGroupTouched (FormControls: { [key: string]: AbstractControl } | AbstractControl[]): void {
const markFormGroupTouchedRecursive = (controls: { [key: string]: AbstractControl } | AbstractControl[]): void => {
_.forOwn(controls, (c, controlKey) => {
if (c instanceof FormGroup || c instanceof FormArray) {
markFormGroupTouchedRecursive(c.controls);
} else {
c.markAsTouched();
}
});
};
markFormGroupTouchedRecursive(FormControls);
}
我 运行 遇到了同样的问题,但我不想 "pollute" 我的组件包含处理此问题的代码。特别是因为我需要以多种形式使用它并且我不想在各种场合重复代码。
因此我创建了一个指令(使用目前发布的答案)。该指令装饰了 NgForm 的 onSubmit
-Method:如果表单无效,它会将所有字段标记为已触及并中止提交。否则通常的 onSubmit-Method 会正常执行。
import {Directive, Host} from '@angular/core';
import {NgForm} from '@angular/forms';
@Directive({
selector: '[appValidateOnSubmit]'
})
export class ValidateOnSubmitDirective {
constructor(@Host() form: NgForm) {
const oldSubmit = form.onSubmit;
form.onSubmit = function (): boolean {
if (form.invalid) {
const controls = form.controls;
Object.keys(controls).forEach(controlName => controls[controlName].markAsTouched());
return false;
}
return oldSubmit.apply(form, arguments);
};
}
}
用法:
<form (ngSubmit)="submit()" appValidateOnSubmit>
<!-- ... form controls ... -->
</form>
这是我实际使用的代码。
validateAllFormFields(formGroup: any) {
// This code also works in IE 11
Object.keys(formGroup.controls).forEach(field => {
const control = formGroup.get(field);
if (control instanceof FormControl) {
control.markAsTouched({ onlySelf: true });
} else if (control instanceof FormGroup) {
this.validateAllFormFields(control);
} else if (control instanceof FormArray) {
this.validateAllFormFields(control);
}
});
}
遍历表单控件并将它们标记为已触摸也可行:
for(let i in this.form.controls)
this.form.controls[i].markAsTouched();
此代码适用于我:
markAsRequired(formGroup: FormGroup) {
if (Reflect.getOwnPropertyDescriptor(formGroup, 'controls')) {
(<any>Object).values(formGroup.controls).forEach(control => {
if (control instanceof FormGroup) {
// FormGroup
markAsRequired(control);
}
// FormControl
control.markAsTouched();
});
}
}
关于@masterwork 的回答。 我尝试了该解决方案,但是当函数尝试递归地挖掘 FormGroup 内部时出现错误,因为在这一行传递了 FormControl 参数而不是 FormGroup:
control.controls.forEach(c => this.markFormGroupTouched(c));
这是我的解决方案
markFormGroupTouched(formGroup: FormGroup) {
(<any>Object).values(formGroup.controls).forEach(control => {
if (control.controls) { // control is a FormGroup
markFormGroupTouched(control);
} else { // control is a FormControl
control.markAsTouched();
}
});
}
无需递归的解决方案
对于那些担心性能的人,我想出了一个不使用递归的解决方案,尽管它仍然迭代所有级别的所有控件。
/**
* Iterates over a FormGroup or FormArray and mark all controls as
* touched, including its children.
*
* @param {(FormGroup | FormArray)} rootControl - Root form
* group or form array
* @param {boolean} [visitChildren=true] - Specify whether it should
* iterate over nested controls
*/
public markControlsAsTouched(rootControl: FormGroup | FormArray,
visitChildren: boolean = true) {
let stack: (FormGroup | FormArray)[] = [];
// Stack the root FormGroup or FormArray
if (rootControl &&
(rootControl instanceof FormGroup || rootControl instanceof FormArray)) {
stack.push(rootControl);
}
while (stack.length > 0) {
let currentControl = stack.pop();
(<any>Object).values(currentControl.controls).forEach((control) => {
// If there are nested forms or formArrays, stack them to visit later
if (visitChildren &&
(control instanceof FormGroup || control instanceof FormArray)
) {
stack.push(control);
} else {
control.markAsTouched();
}
});
}
}
此解决方案适用于 FormGroup 和 FormArray。
您可以在这里尝试一下:angular-mark-as-touched
参见this gem。 迄今为止我见过的最优雅的解决方案。
完整代码
import { Injectable } from '@angular/core';
import { FormGroup } from '@angular/forms';
const TOUCHED = 'markAsTouched';
const UNTOUCHED = 'markAsUntouched';
const DIRTY = 'markAsDirty';
const PENDING = 'markAsPending';
const PRISTINE = 'markAsPristine';
const FORM_CONTROL_STATES: Array<string> = [TOUCHED, UNTOUCHED, DIRTY, PENDING, PRISTINE];
@Injectable({
providedIn: 'root'
})
export class FormStateService {
markAs (form: FormGroup, state: string): FormGroup {
if (FORM_CONTROL_STATES.indexOf(state) === -1) {
return form;
}
const controls: Array<string> = Object.keys(form.controls);
for (const control of controls) {
form.controls[control][state]();
}
return form;
}
markAsTouched (form: FormGroup): FormGroup {
return this.markAs(form, TOUCHED);
}
markAsUntouched (form: FormGroup): FormGroup {
return this.markAs(form, UNTOUCHED);
}
markAsDirty (form: FormGroup): FormGroup {
return this.markAs(form, DIRTY);
}
markAsPending (form: FormGroup): FormGroup {
return this.markAs(form, PENDING);
}
markAsPristine (form: FormGroup): FormGroup {
return this.markAs(form, PRISTINE);
}
}
从Angular 8你可以简单地使用
this.form.markAllAsTouched();
将控件及其子控件标记为已触摸。
从 Angular v8 开始,您在 markAllAsTouched
方法的帮助下得到了这个 built-in。
举个例子,你可以这样使用它
form.markAllAsTouched();
查看官方文档:https://angular.io/api/forms/AbstractControl#markallastouched
/**
* Marks as a touched
* @param { FormGroup } formGroup
*
* @return {void}
*/
markFormGroupTouched(formGroup: FormGroup) {
Object.values(formGroup.controls).forEach((control: any) => {
if (control instanceof FormControl) {
control.markAsTouched();
control.updateValueAndValidity();
} else if (control instanceof FormGroup) {
this.markFormGroupTouched(control);
}
});
}
查看:
<button (click)="Submit(yourFormGroup)">Submit</button>
API
Submit(form: any) {
if (form.status === 'INVALID') {
for (let inner in details.controls) {
details.get(inner).markAsTouched();
}
return false;
}
// as it return false it breaks js execution and return
我制作了一个版本,对所呈现的答案进行了一些改动,对于那些使用旧版本8的angular,我想分享给那些有用的人。
效用函数:
import {FormControl, FormGroup} from "@angular/forms";
function getAllControls(formGroup: FormGroup): FormControl[] {
const controls: FormControl[] = [];
(<any>Object).values(formGroup.controls).forEach(control => {
if (control.controls) { // control is a FormGroup
const allControls = getAllControls(control);
controls.push(...allControls);
} else { // control is a FormControl
controls.push(control);
}
});
return controls;
}
export function isValidForm(formGroup: FormGroup): boolean {
return getAllControls(formGroup)
.filter(control => {
control.markAsTouched();
return !control.valid;
}).length === 0;
}
用法:
onSubmit() {
if (this.isValidForm()) {
// ... TODO: logic if form is valid
}
}
根据@masterwork
angular 版本 8
的打字稿代码private markFormGroupTouched(formGroup: FormGroup) {
(Object as any).values(formGroup.controls).forEach(control => {
control.markAsTouched();
if (control.controls) {
this.markFormGroupTouched(control);
}
}); }