(对焦)在Firefox和Chrome中的行为有所不同

时间:2019-04-21 14:25:31

标签: angular

如果字段为空,我正在通过添加红色边框对自定义上传按钮进行表单验证。 在chrome和firefox中打开以下演示链接。单击上载按钮,关闭上载窗口,然后单击其他任何地方以松开焦点。将显示红色边框,因为它为空并标记为已触摸。现在,在Chrome上执行相同的操作,只要单击我不想要的上传按钮,红色边框就会立即显示。我想要在Firefox上出现的行为。

DEMO https://stackblitz.com/edit/angular-m2hmua

<form [formGroup]="cForm" (ngSubmit)="onSubmit()">
  <input type=text placeholder="name" formControlName="name"
  [ngClass]="{'err-border': (cForm.controls.name.errors?.required && cForm.controls.name.touched) || cForm.controls.name.errors?.required && submitted}" 
  >
  <br><br><br>
  <input type="button" type="file" formControlName="file" id="realInput" style="display: none">
  <button type="button" id="fakeBtn"
  [ngClass]="{'err-border': (cForm.controls.file.errors?.required && submitted) || (cForm.controls.file.errors?.required && cForm.controls.file.touched)}"
  (focusout)="focusFunction()"
  >Upload</button>
  <span id="text">No file selected</span>
  <br><br><br>
  <button type="submit" >Submit</button>
</form>

TS

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {
  cForm: FormGroup;
  submitted = false;
  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.cForm = this.formBuilder.group({
      name: ['', Validators.required],
      file: ['', Validators.required]
    });
    var realInput = document.querySelector('#realInput');
    var fakeBtn = document.querySelector('#fakeBtn');
    var text = document.querySelector('#text');
    fakeBtn.addEventListener("click", function(){
       // @ts-ignore
      realInput.click();

       })
       realInput.addEventListener("change", function(event) {
       // @ts-ignore
      if(realInput.value) {
         // @ts-ignore
        text.innerHTML = event.target.files[0].name;
      } else {
          text.innerHTML = "No file selected";
      }
       });
       fakeBtn.addEventListener("click", ()=> {
         this.submitted = false;
            // @ts-ignore
     document.querySelector('#realInput').value = "";
     this.cForm.controls.file.reset();
       // @ts-ignore
      document.querySelector('#text').innerHTML = "No file";
       });

  }
onSubmit() {
  this.submitted = true;
  if(this.cForm.invalid) {
    return;

  }
  console.log(this.cForm.value);
}

focusFunction(){
  //console.log('inside focus function, touched:',this.cForm.controls.file);
  this.cForm.controls.file.markAsTouched();
}

}

0 个答案:

没有答案