如何使用可选值设置输入样式
How to style Input with optional value
我有一个带有可选值的输入字段(不是必需的)。当我与它互动时,我得到 类 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
has-value 检查 all formControls 的最佳方法是什么?或者有其他方法可以做到这一点吗?
我不希望 input.ng-valid.ng-dirty
选择器影响不需要的输入,但用户输入并删除了一些东西(使它们 dirty
、touched
、valid
).
我是用这个指令做的:
/* 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 !== '');
}
}
}
我有一个带有可选值的输入字段(不是必需的)。当我与它互动时,我得到 类 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
has-value 检查 all formControls 的最佳方法是什么?或者有其他方法可以做到这一点吗?
我不希望 input.ng-valid.ng-dirty
选择器影响不需要的输入,但用户输入并删除了一些东西(使它们 dirty
、touched
、valid
).
我是用这个指令做的:
/* 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 !== '');
}
}
}