【问题标题】:<input type="date"> not validating when value changes in Firefox for Android<input type="date"> 在 Firefox for Android 中的值更改时不进行验证
【发布时间】:2018-01-08 13:23:22
【问题描述】:

在将 Firefox(版本 54 和 55)用于 Android 或桌面并将 dom.forms.datetime 标志设置为 true 时。它打开一个日历模式,供用户选择日期。但是当用户选择日期时,验证不会更新并且提交按钮继续禁用。

my.component.html:

<input id="deadline" 
       type="date" 
       class="form-control"
       name="deadline" 
       placeholder="yyyy-mm-dd" 
       formControlName="deadline">

<button type="submit" class="btn btn-primary" [disabled]="!newForm.valid">
      save
</button>

my.component.ts:

ngOnInit() {
    this.newForm = new FormGroup({
        deadline: new FormControl('', Validators.compose([
            Validators.required,
            Validators.pattern('[0-9]{4}-[0-9]{2}-[0-9]{2}')
        ]))
    });
}

我怎样才能做到这一点?

【问题讨论】:

标签: android html angular firefox angular2-forms


【解决方案1】:

发生这种情况是因为 Firefox for Android 仅在用户从日期选择器中选择日期后触发更改但不触发输入事件。 DefaultValueAccessor in Angular relies on the input event。结果,表单控件的值不会更新,而是保持null

作为一种解决方法,您可以添加一个调用 FormControl 的 setValue() 的 onchange 侦听器。

my.component.ts:

    @ViewChild('input')
    private input: ElementRef;

    @HostListener('change')
    private missingInputWorkaround() {
        const formCtrl = this.newForm.get('deadline');
        if (this.isBrowserWithoutInputEvent() && this.input.nativeElement.value !== formCtrl.value) {
            formCtrl.setValue(this.input.nativeElement.value);
        }
    }

    private isBrowserWithoutInputEvent() {
        // Firefox for Android (Fennec)
        return /\(Android .+ Firefox\/\d+/i.test(navigator.userAgent);
    }

【讨论】:

  • 只需要在元素中包含那个#input。编辑答案以反映它。谢谢!
猜你喜欢
  • 2016-11-25
  • 1970-01-01
  • 2016-01-13
  • 2018-10-05
  • 2023-03-23
  • 2013-05-29
  • 1970-01-01
  • 2021-06-25
  • 2020-10-28
相关资源
最近更新 更多