In Angular 1 (1.5) the form controller had a $setSubmitted()
method that allowed you to programmatically set the .$submitted
flag to true.
How can I do this in 2 via the NgForm object? I do not want to use the template, aka (ngSubmit)=""
.
I've tried <formname>.ngSubmit.emit()
, but it does not set .submitted
to true.
In this article, we are going to see what is NgForm in Angular 10 and how to use it. NgForm is used to create a top-level form group Instance, and it binds the form to the given form value. In app.module.ts import FormsModule. In app.component.html make a form and store its value in ngForm variable and show its value in a JSON form.
To import the FormsModule but skip its usage in some forms, for example, to use native HTML5 validation, add the ngNoForm and the <form> tags won't create an NgForm directive. In reactive forms, using ngNoForm is unnecessary because the <form> tags are inert.
In the context of NgForm, the role of NgModel is to register the form field with form using name attribute. NgModel is also used to bind the domain model of the class with view. On this page we will provide how to enable using NgForm in our angular application.
On form submit, the form values can be accessed in class as given below. If we use neither one-way binding not two-way binding still we need to use ngModel attribute in fields when using with parent form as given below. Then this field will not be registered with parent form and its value will not be passed to our class on form submit.
ngSubmit
is actually an event emitter (an @Output()
binding) that will notify you after form has been submitted - it does this by listening to the DOM event for submit on the host form element.
So even if you don't use ngSubmit
the form will still be 'submitted` if the user clicks a submit button within the form.
You can set the form submitted flag to to true
manually using the onSubmit
method e.g. via a button
<button type="button" (click)="theForm.onSubmit($event)">Submit</button>
.. but in my experience with Angular forms this would be quite unusual to need to set this manually (the ngForm
directive and ngSubmit
event emitter should be all you need to manage the form). Is there a reason why you would need this?
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