Angular 2 - Forms - Set NgForm .submitted to true

2019-04-08 09:34发布

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.

3条回答
放我归山
2楼-- · 2019-04-08 10:09

I'm doing a workaround:

 <form #form="ngForm" [formGroup]='toiletForm' [class.submitted]='submitted'></form>

Component prop:

submitted: boolean;

.less:

form.submitted input.ng-invalid {
    border: solid 2px #fa787e !important;
}
查看更多
Summer. ? 凉城
3楼-- · 2019-04-08 10:12

To submit form on click of button which is outside of form this same method can be used. While creating the form assign a Reference variable to the form

<form name = "myform" (ngSubmit)= "SubmitForm()" #formVar = "ngForm">.....</form>

Now we can use this "formVar" throughout the html to directly access the form. For submitting on click of button outside of form (using ngSubmit directive of angular form) use this.

<button (click)= "formVar.onSubmit($event)"> Submit </button>
查看更多
Root(大扎)
4楼-- · 2019-04-08 10:15

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?

查看更多
登录 后发表回答