Update form values both on blur and submit in Angu

2019-04-07 21:51发布

问题:

I am implementing a reactive form in Angular 5, and I need to trigger validation in both events, when the fields are blurred and also when the form is submitted.

I have set it to blur using the updateOn property to 'blur', but if you are focused on a field and press enter, the blur event is not triggered, and the value of the field is not updated, unless I click away from the field.

As far as I know there is no way of settingn updateOn to both blur and submit.

Is there any way of achieving this?

回答1:

The easiest way is to focus on some element when submitting. The more appropriate is submit button I think.

<form #form="ngForm" (ngSubmit)="submitBtn.focus(); submit()" [ngFormOptions]="{ updateOn: 'blur' }" novalidate>
  ...
  <button type="submit" #submitBtn>
</form>