How to style Input with optional value

我是研究僧i 提交于 2020-01-15 07:08:09

问题


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

What's the best way to do has-value check for all formControls? Or is there some other way to do this?

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).


回答1:


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 !== '');
    }
  }
}


来源:https://stackoverflow.com/questions/40087779/how-to-style-input-with-optional-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!