<input type="date"> 在 Firefox 中为 Android 更改值时未验证

<input type="date"> not validating when value changes in Firefox for Android

当 Android 或桌面使用 Firefox(版本 54 和 55)并将 dom.forms.datetime 标志设置为 true 时。它为用户 select 日期打开日历模式。但是当用户 selects 验证未更新的日期并且提交按钮继续禁用时。

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 的 Firefox 在用户从日期选择器中选择日期后仅触发更改但没有输入事件。 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);
    }