简体   繁体   English

表单验证失败后如何显示模式?

[英]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. 在Angular中使用反应式表单时,我们通常会在教程中看到同步验证器以及表单控件下带有错误的小<p><span> This element has a simple *ngIf that controls its display. 这个元素有一个简单的*ngIf来控制其显示。

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 ). 根据我在ng-bootstrap和ngx-bootstrap中看到的内容,模态已打开,调用了一个函数,并且未完全侦听验证中的更改(使用<p>*ngIf可以轻松完成此*ngIf )。

Currently, I use a change listener in my form control, which calls the API that validates it. 当前,我在表单控件中使用了一个更改侦听器,该侦听器调用用于验证它的API。 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. 如果API返回无效,我将引发一个包含在表单控件的同步验证器中的标志(因此使整个表单无效),然后从那里也打开模式。 (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: 如果你已经有了一个异步验证连接,你必须使用statusChanges FormControl的财产,与distinctUntilChanged管,以防止重复:

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. 我喜欢使用ngx-smart-modal库进行这种模式的内务处理。

Docs => https://www.npmjs.com/package/ngx-smart-modal 文件=> 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. 当涉及模态时,该库使管理打开/关闭/数据传递/定制/等非常容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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