模型驱动表单 - IE11 上的输入占位符问题

2023-12-21

我已将我的应用程序从 Angular 2.x 更新到 Angular 4.0.0。从现在开始,我遇到输入类型文本表单控件的以下问题:


在 IE11 上,当接收到焦点时,占位符将被删除,表单控件将设置为 dirty,并将 pristine 设置为 false。 在 Chrome / FF 上,这个问题永远不会发生。

在 IE11 上,输入元素一旦获得焦点就会变脏。与 Chrome 不同的是,你必须先输入它。

HTML :

<input 
  type="text" 
  class="form-control" 
  id="processName" 
  [(ngModel)]="process.displayName" 
  [disabled]="isProcessLoading"
  #processName="ngModel"
  maxLength="64" 
  pattern="^.*\S.*" 
  name="processName" 
  placeholder="{{'PROCESS-FORM.name-placeholder' | translate}}"
  required 
  placeholderRequired 
  [inputBinding]="processName" 
/>

我创建了一个指令,当处于焦点时,它将所有错误设置为 null(有效)。

@Directive({
  selector: '[placeholderRequired]'
})
export class PlaceHolderDirective {
  @Input() inputBinding: any = null;

  constructor(private elementRef: ElementRef) {
  }

  @HostListener('focus', ['$event'])
  handleFocus(event: any) {
    if (navigator.appVersion && navigator.appVersion.indexOf('.NET') > -1) {
      // IE only
      if (!this.inputBinding._control._value) {
        this.inputBinding.control.setErrors(null);
        setTimeout(() => this.inputBinding.control.setErrors(null),0);
      }
    }
  }

  @HostListener('mousedown', ['$event'])
  handleMouseDown(event: any) {
    if (navigator.appVersion && navigator.appVersion.indexOf('.NET') > -1) {

      if (!this.inputBinding._control._value) {
        this.inputBinding.control.setErrors(null);
        setTimeout(() => this.inputBinding.control.setErrors(null),0);
      }
    }
  }

  @HostListener('blur', ['$event'])
  handleBlur(event: any) {
    if (navigator.appVersion && navigator.appVersion.indexOf('.NET') > -1) {
      if (!this.inputBinding._control._value.trim()) {
        // handle blur event
      }
    }
  }
}

当用户单击输入字段时,从角度 valueAccessor.onValueChanged() 的某个位置,使用 control.markAsDirty() 将该字段标记为脏。

我也添加了 setTimeout() ,但它在之后执行 执行 markAsDirty(),这会导致 UI 几乎没有波动(脏 真 -> 肮脏的假)。

可以用其他方法解决这种行为吗? 有什么方法可以覆盖 onValueChanges() 因为它在内部将字段设置为脏。不需要添加其他库(如 placeholder.js)。


我定制了原始的如下:

ts file

iePristine: boolean = true;
pincodeCtrl = <formControl>this.form.get('pincode')
  setPlaceholder() {
    const placeholder = 'Enter Code';
    if (this.pincodeCtrl.value) {
      this.iePristine = false;
    }
    if (this.iePristine) {
      this.pincodeCtrl.markAsPristine();
    }
    return placeholder;
  }

isInvalidControl(control: FormControl) {
    return control.invalid && (control.dirty || control.touched);
  }

html文件

<input type="text" [placeholder]="setPlaceholder()" formControlName="pincode"
            [ngClass]="isInvalidControl(pincodeCtrl) ? 'form-control text-center is-invalid' : 'form-control text-center'" />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

模型驱动表单 - IE11 上的输入占位符问题 的相关文章

随机推荐