We have an Angular 4 app, where we have a template driven form, which consists of multiple custom components (i.e. our custom-input tag). Within those custom components we need to know if the form is already submitted or not. So we can show some error text, within the component. So this logic from our custom component has been working until now with Angular 4 and Template Driven Forms:
const classes = this.elementRef.nativeElement.className;
And classes have for instance ng-dirty, ng-touched, ng-invalid and submitted (when the form is submitted). So angular was adding the class 'submitted' automatically for every form field, when the form is submitted.
Now We try to build another Angular app, with Version 5, with reactive forms. We have the same concept, but from the components (actually from the html - since we use nativeElement) we somehow do not get any clue about the submit. We can of course give in the information from the form to custom elements, but we dont want to write the same on every form component. Imagine the form has 50 fields..
Is there any other option?
With reactive forms, you build your own representation of a form in the component class. Note: Reactive forms were introduced with Angular 2. In this article, you will explore how reactive forms can be applied to an example Angular application. If you would like to follow along with this article, you will need:
Template-driven forms are the default way to work with forms in Angular. With template-driven forms, template directives are used to build an internal representation of the form. With reactive forms, you build your own representation of a form in the component class.
Custom Form Controls Custom form controls/inputs are a typical pattern in complex Angular applications. It's common to want to encapsulate HTML, CSS, and accessibility in an input component to make it easier to use in forms throughout the application. Common examples of this are datepickers, switches, dropdowns, and typeaheads.
We can see our custom app-switch works seamlessly with the Reactive Forms/Form Builder API just like any other text input. NgModel allows us to bind to an input with a two-way data binding syntax similar to Angular 1.x. We can use this same syntax when using a custom form control.
There is no such property which can tell you the form is submitted or not, you need to create a variable and keep status of your form like
isSubmitted: boolean = false;
On save method
save(...){
this.isSubmitted = true;
...............
}
See the below link for more detail
angular 5 form validation easiest way
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With