angular - Reactive Forms - mark fields as touched -
i having trouble finding out how mark form's fields touched. main problem if not touch fields , try submit form - validation error in not shown up. have placeholder piece of code in controller.
idea simple:
- user clicks submit button
- all fields marks touched
- error formatter reruns , displays validation errors
if have other idea how show errors on submit, without implementing new method - please share them. thanks!
my simplified form:
<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>
and controller:
import {component, oninit} '@angular/core'; import {formgroup, formbuilder, validators} '@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 required.' } }; constructor(private fb: formbuilder) { } ngoninit(): void { this.buildform(); } onsubmit(form: any): void { // somehow touch elements onvaluechanged 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; (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]; (const key in control.errors) { if (!control.errors.hasownproperty(key)) { continue; } this.formerrors[field] += messages[key] + ' '; } } } } }
the following function recurses through controls in form group , gently touches them. because controls field object, code call object.values() on form group's control field.
/** * marks controls in form group touched * @param formgroup - group caress..hah */ private markformgrouptouched(formgroup: formgroup) { (<any>object).values(formgroup.controls).foreach(control => { control.markastouched(); if (control.controls) { control.controls.foreach(c => this.markformgrouptouched(c)); } }); }
Comments
Post a Comment