简体   繁体   中英

How can I show a modal after failed form validation?

When using reactive forms in Angular, we usually see in tutorials sync validators and a small <p> or <span> under the form control with the error. This element has a simple *ngIf that controls its display.

Nevertheless, I need to display a modal when an async validator fails. From what I see in ng-bootstrap ang ngx-bootstrap, the modal is opened calling a function, and doesn't exactly listen to changes in the validation (which I can do easily with the <p> and *ngIf ).

Currently, I use a change listener in my form control, which calls the API that validates it. If the API returns invalid, I raise a flag that I included in the sync validators of my form control (hence making the whole form invalid), and open the modal from there too. (Ultimately I'm not using an async validator).

That code smells funny to me.

Is there a better way to do this? Thanks!

If you already has an async validator attached, you have to use the statusChanges property of FormControl, with the distinctUntilChanged pipe to prevent duplication:

this.userForm.get('username').statusChanges
  .pipe(distinctUntilChanged())
  .subscribe(status => {
     // if status is invalid, open dialog or whatever yo like
     console.log('Username validation status: '+ status);
  }); 

I like to use the ngx-smart-modal library for this kind of modal housekeeping.

Docs => https://www.npmjs.com/package/ngx-smart-modal

This library makes it very easy to manage opening/closing/data delivery/customization/etc when it comes to modals.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM