I have created template driven form in Angular.
<form novalidate #f="ngForm" (ngSubmit)="onSubmit(f)">
<input type="text" class="form-control" name="fullName" #fullName="ngModel" required>
<div *ngIf="fullName.errors?.required && fullName.touched" class="validation-message">Required</div>
<button type="submit">Post</button>
It shows error when it is invalid and touched. I need to display error when form is submitted i.e. when the submit button is clicked.
onSubmit({value, valid}): void {
if (valid) {
console.log(value);
} else {
console.log('invalid form');
}
}
esnezz :
In onSubmit method iterate through all form controls and simply mark them as touched\n\nObject.keys(form.controls).forEach(key => {\n form.controls[key].markAsTouched();\n});\n",
2019-10-14T19:12:27
Vega :
Set a flag to be true when it's valid and use $ngIf:\nHTML\n\n<form #myForm=\"ngForm\" (submit)=\"onSubmit(myForm)\">\n <input type=\"text\" class=\"form-control\" required [(ngModel)]=\"fullname\" name=\"fullname\" #input=\"ngModel\">\n <div style=\"color:red\" *ngIf=\"submittedError\">\n Error\n </div>\n <br><br>\n <button type=\"submit\">Post</button>\n</form>\n\n\nTypescript:\n\nsubmittedError;\n... \nonSubmit({value, valid}): void {\n if (valid) {\n this.submittedError=false;\n console.log(value);\n } else {\n this.submittedError=true;\n console.log('invalid form');\n }\n }\n}\n\n\ndemo",
2018-06-08T01:02:53
Hyuck Kang :
You have to use an extra flag to do that.\n\nLike below,\n\nsubmitted = false;\nonSubmit() { this.submitted = true; }\n\n\nAnd insert submitted into *ngIf statement.\n\nReference :\nhttps://angular.io/guide/forms#toggle-two-form-regions-extra-credit",
2018-06-08T01:04:44