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