lundi 19 août 2019

Angular Custom Directive not returning specific value

I am trying to implement a custom directive that will apply checks depending on different conditions and it contains the array of files to be uploaded.After getting the updated control values in custom-validator file,return function is not returning the expected output.

In order to get the updated control, I am using promise and timeout.

upload-file.component.html

<input formControlName="document"  
style="display: none" type="file" 
multiple  (change)="onFileChange($event)" #fileInput 
accept="application/pdf"  class="form-control">

<button class="btn upload-doc-btn" 
(click)="fileInput.click()"><span><i class="material- 
icons">vertical_align_top</i> Upload File</span></button>

upload-file.component.js

export class UploadFileComponent implements OnInit {

allowedExtensions: string;
selectedFile: string;
documentCount: number;
documentNameArr = [];

private validateDocumentForm: FormGroup;

@Input() fileTypeAllowed: string;

constructor(
  private fileUploadService: FileUploadService,
  private formBuilder: FormBuilder,
  private cd: ChangeDetectorRef
) {
}

ngOnInit() {
  this.documentCount = 0;

  this.validateDocumentForm = this.formBuilder.group({
    document: ['', CustomValidator.uploadFile('pdf', 4)]
  });
}


onFileChange(event) {
  this.validateDocumentForm.controls.document.files = event.target.files;
}

/**
 * Getter for form control
 */

get f() {
  return this.validateDocumentForm.controls;
}}

CustomValidator.js

export class CustomValidator {

static uploadFile(fileType: string, limit = 1, isFiled = false): ValidatorFn | null {
return (control: AbstractControl) => {
  let files = null;
  let isFileArr = false;
  files = control.files;

  myFun();

  function myFun() {
    const promise1 = new Promise(function(resolve, reject) {
      setTimeout(function() {
        //  @ts-ignore
        files = control.files;
        if ( files !== undefined && files.length > 0) {
          isFileArr = true;
        }
        resolve(files);
      }, 300);
    });

    promise1.then(function(value) {
      return value;
    });
  }


  function test() {
    if (isFileArr) {
        console.log('works'); //it works i.e console is printed but it doesn't return any value
      return {
        fileUploadLimit: limit
      };
    }

    // Below commented code returns the value as expected but it's not working with 'if case' as demonstrated above.

    // return {
    //   fileUploadLimit: limit
    // };
  }
  // @ts-ignore
  setTimeout(test, 1000);
  return test();

};}}

Aucun commentaire:

Enregistrer un commentaire