角形+引导程序“无效",“有效" [英] angular forms + bootstrap 'is-invalid', 'is-valid'

查看:66
本文介绍了角形+引导程序“无效",“有效"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,我有一个小巧的形式,并使用了反应性方法 例如,我有两个输入

Imagine I have a small form and use reactive approach For example, I have two inputs

...
<input formControlName="name" name="name" type="text" class="form-control">
<input formControlName="amount" name="amount" type="text" class="form-control">
...

我想跟踪更改并在适当的情况下添加引导类"is-valid"/"is-invalid". 问题是我看到的唯一可以做到的方法是:

I want to track changes and add bootstrap classes 'is-valid'/ 'is-invalid' for appropriate cases. The problem is that the only way I see I can do it is this:

<input formControlName="name" name="name" type="text" class="form-control"
                 [ngClass]="name.invalid && name.touched ? 'is-invalid' : ''">

在ts文件中:

ngOnInit() {
    ...
    this.name = this.shoppingListForm.get('name');
  }

有没有更好的方法.对我来说真正令人讨厌的是html中有很多泥浆".

Is there a better approach. What is really annoying for me is a lot of "mud" in html.

因此,如果表单应具有默认样式,则意味着页面已加载并 输入没有被触及

So, if form should has default style, it means the page was loaded and input wasn't touched

我发现我可以做到这一点,但仍然猜测有更好的方法. 更好"是指不会使html变脏

I found out that I can do this, but still guess there is a better approach. By "better" I mean that won't make html so dirty

<input formControlName="name" name="name" type="text" class="form-control"
[ngClass]="{'is-invalid': name.invalid && name.touched, 
            'is-valid': name.valid, '': name.untouched}"

感谢您的帮助)

如下面的@Muhammed所述,做我需要的最好方法是通过CSS

As @Muhammed stated below, the best way to do what I need is to do it through css

在引导4的情况下,我的贡献很小.

Just small contribution of mine in case of bootstrap 4.

问题在于它会添加边框阴影,因此对我来说,完整的解决方案是: 无效输入

The problem is that it adds border shadow, so the complete solution for me is this: for invalid input

input.ng-invalid.ng-touched{ 
    border-color: rgba(255,10,29,1) !important; box-shadow: none !important; 
} 

如果聚焦,则使边框看起来不错

if it is focused, then make border look good

input.ng-invalid.ng-touched:focus{ 
    box-shadow: 0 0 0 0.2rem rgba(255,10,29,0.25) !important; 
}

推荐答案

您不需要添加与表单控件状态更改相关的任何类,默认情况下,只需添加与这些类相关的样式

You don't need to add the any class related to form control state change angular do this by default you just need to add a style related to these classes

input.ng-invalid.ng-touched {
    border: 1px solid red;
 }

此类表明输入控件无效且已敲击,这意味着您只需要处理样式即可.

this class indicate the input control is invalid and toched , this mean you just need to work on the style.

这篇关于角形+引导程序“无效",“有效"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆