Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Forms - Set NgForm .submitted to true via NgForm Object

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.

like image 908
mrshickadance Avatar asked Oct 04 '17 17:10

mrshickadance


People also ask

What is ngform in angular 10 and how to use it?

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.

How do I use ngnoform with formsmodule?

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.

What is the role of ngmodel in angular form?

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.

How to access form values in form submit using ngmodel?

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.


1 Answers

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?

like image 71
Garth Mason Avatar answered Nov 15 '22 04:11

Garth Mason