如何将伪类有效/无效与Angular表单控件验证器混合使用? [英] How to mix pseudo class valid/invalid with Angular form control validator?

查看:63
本文介绍了如何将伪类有效/无效与Angular表单控件验证器混合使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Agular表单控件来控制选择"有效性.当所述选择"无效时,可以在选择"上找到类"ng-invalid".当选择"有效时,类别为"ng-valid".

I'm using an Agular form control to control a "select" validity. When said "select" is invalid, class "ng-invalid" can be found on the "select". Class "ng-valid" is, when "select" is valid.

但是,伪类无论哪种方式都保持:valid".问题是我正在使用第三方库来存储样式,该库基于伪类来处理样式.

However, pseudo class remains ":valid" either way. The problem is I'm using a third party library for style which is based on pseudo classes to handle style.

看看这个例子, https://stackblitz.com/edit/angular-xypbcc

我想当类为"ng-invalid",而select为空时,伪类:invalid apply(它是css样式).(我知道我可以将require添加到select元素中,但实际上我的实际用例中还有其他验证器)

I'd like that the pseudo class :invalid apply (and it's css style), when class is "ng-invalid", when select is empty. (I know I could add the required to the select element, but I actually have other validators in my real use case)

谢谢

推荐答案

最简单的方法是将非活动状态的.css复制到.ng-invalid

the easy way is copy the .css of inactive to .ng-invalid

一种解决方法是使用 setCustomValidity 您可以使用指令

A work-around is use setCustomValidity You can use a directive

@Directive({
  selector: "[invalid]"
})
export class InvalidDirective implements OnInit, OnDestroy {
  subscription$: any;
  @Input("invalid") checkAtFirst: boolean = false;
  constructor(private control: NgControl, private el: ElementRef) {}
  ngOnInit() {
    this.subscription$ = this.control.statusChanges.subscribe(res => {
      this.el.nativeElement.setCustomValidity(res == "INVALID" ? "error" : "");
    });
    if (this.checkAtFirst && this.control.invalid)
      this.el.nativeElement.setCustomValidity("error");
  }
  ngOnDestroy() {
    this.subscription$.unsubscribe();
  }
}

指令将ngControl(输入)和elementRef(HTMLElement)注入到构造函数中,并订阅statusChange.如果您要先检查,请使用输入内容

The directive inject in the constructor the ngControl (the input) and the elementRef (the HTMLElement) and subscribe to statusChange. I use the input if you want to check at first

所以您使用

 <select invalid=true formControlName="fcselect">
//or
 <select invalid formControlName="fcselect">

您可以在 stackblitz <中看到示例/a>

You can see the example in the stackblitz

这篇关于如何将伪类有效/无效与Angular表单控件验证器混合使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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