如何使用可选值设置输入的样式 [英] How to style Input with optional value
本文介绍了如何使用可选值设置输入的样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有可选值的输入字段(不是必需的).与之交互时,我得到了类ng-dirty
,ng-valid
,ng-touched
I have an input field with optional value (not required). When I interact with it, I get classes ng-dirty
, ng-valid
, ng-touched
<input type="text" formControlName="url"
[class.has-value]="quickSetupForm.controls.url.value !== ''"
placeholder="www.example.com"
id="url">
input.ng-valid.ng-dirty.has-value
border-bottom 2px solid green
检查所有 formControl的最佳方法是什么?还是有其他方法可以做到这一点?
What's the best way to do has-value check for all formControls? Or is there some other way to do this?
我不希望input.ng-valid.ng-dirty
选择器影响不需要的输入,但是用户已输入并删除了某些内容(将其设置为dirty
,touched
,valid
).
I don't want input.ng-valid.ng-dirty
selector to affect inputs that are not required, but user has entered and deleted something (making them dirty
, touched
, valid
).
推荐答案
我是通过以下指令做到的:
I did it with this directive:
/* tslint:disable:directive-selector-prefix */
import { Directive, ElementRef, HostListener, Renderer } from '@angular/core';
@Directive({
selector: '[formControlName]'
})
export class FormControlValueDirective {
private control: HTMLInputElement;
constructor(
private renderer: Renderer,
private elementRef: ElementRef) {
this.control = this.elementRef.nativeElement;
}
@HostListener('input') onInput() {
if (this.control instanceof HTMLInputElement) {
this.renderer.setElementClass(this.control, 'has-value', this.control.value !== '');
}
}
}
这篇关于如何使用可选值设置输入的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文