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

问题描述 投票:4回答:1

我已将我的应用程序从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
      }
    }
  }
}

当用户在angular valueAccessor.onValueChanged()的某处点击输入字段时,使用control.markAsDirty()将该字段标记为脏。

我也添加了setTimeout(),但是在执行markAsDirty()之后执行它会导致UI的波动很小(dirty true - > dirty false)。

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

javascript html5 angular internet-explorer angular2-forms
1个回答
0
投票

我定制了原始如下:

ts文件

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'" />
© www.soinside.com 2019 - 2024. All rights reserved.