Answers for "reactive form file input directive"

0

reactive form file input directive

import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[reactiveFileInput]',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: ReactiveFileInputDirective,
      multi: true
    }
  ]
})
export class ReactiveFileInputDirective implements ControlValueAccessor  {

  onChange: Function = () => {};
  public files: FileList | null = null;

  @HostListener('change', ['$event.target.files']) emitFiles(files: FileList) {
    this.files = files;
    this.onChange(files);
  }

  constructor(private host: ElementRef<HTMLInputElement>) {}

  writeValue(value: FileList | null) {
    this.host.nativeElement.value = '';
    this.files = value;
  }

  registerOnChange(fn: Function) {
    this.onChange = fn;
  }

  registerOnTouched(fn: Function) {}

}
Posted by: Guest on October-25-2021

Code answers related to "reactive form file input directive"

Browse Popular Code Answers by Language