简体   繁体   中英

Form Validation not happening on angular 2 for input type=“file”

  <div class="form-group">
    <label for="fileName">Name</label>

    <input type="file" class="form-control" id="fileName"  placeholder="Upload file" accept=".xlsx, .xls"
           required
           [(ngModel)]="model.fileName" name="fileName"
           #fileName="ngModel">
    <div [hidden]="fileName.valid || fileName.pristine" class="alert alert-danger">
      File to be uploaded is required
    </div>
  </div>

Using angularjs2 forms, I am trying to upload a file and submit the form. Even if I choose the file, the control doesn't recognize the selected value.

As others stated, input type=file is not supported (yet?) by Angular. You have some workaround

//template
<input type="file" class="form-control" id="fileName"  placeholder="Upload file" accept=".xlsx, .xls"
           required
           (change)="onImageChangeFromFile($event)">

//component
onImageChangeFromFile(event) {
    if (event.target.files && event.target.files[0]) {
      let file = event.target.files[0];
      //validation here then attribute the value to your model
      this.model = file
    }
  }
 <form >
    <input type="file" class="form-control" id="fileName"  placeholder="Upload 
    file" accept=".txt"required  (change)="onImageChangeFromFile($event)">
 </form>

onImageChangeFromFile(event)
{

    if (event.target.files && event.target.files[0]) {
      let file = event.target.files[0];
        if(file.type == "text/plain") {
          console.log(file.type);
          alert("this is text file");

        }
        else {
           alert("please fill right file");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM