Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 | How to handle input type file in FormControl?

Tags:

forms

angular

Good day,

How can i handle input type file in formControl? im using reactive form but when i get the value of my form it returns null value on my <input type="file">??

like image 918
Jydon Mah Avatar asked Jul 21 '17 07:07

Jydon Mah


2 Answers

You need to write your own FileInputValueAccessor. Here is the plunker and the code:

@Directive({
  selector: 'input[type=file]',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: FileValueAccessorDirective,
      multi: true
    }
  ]
})
export class FileValueAccessorDirective implements ControlValueAccessor {
  onChange;

  @HostListener('change', ['$event.target.value']) _handleInput(event) {
    this.onChange(event);
  }

  constructor(private element: ElementRef, private render: Renderer2) {  }

  writeValue(value: any) {
    const normalizedValue = value == null ? '' : value;
    this.render.setProperty(this.element.nativeElement, 'value', normalizedValue);
  }

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

  registerOnTouched(fn: any) {  }

  nOnDestroy() {  }
}

And then you will be able to get updates like this:

@Component({
  moduleId: module.id,
  selector: 'my-app',
  template: `
      <h1>Hello {{name}}</h1>
      <h3>File path is: {{path}}</h3>
      <input type="file" [formControl]="ctrl">
  `
})
export class AppComponent {
  name = 'Angular';
  path = '';
  ctrl = new FormControl('');

  ngOnInit() {
    this.ctrl.valueChanges.subscribe((v) => {
      this.path = v;
    });
  }
}
like image 199
Max Koretskyi Avatar answered Oct 13 '22 19:10

Max Koretskyi


there is no way to handle this in angular form-control. we can provide some hack to make this work if you want to upload the image. just add the <input type=file> as form control on which user can add the file and acter grabbing the file we can change it to the base64code and then assign that value to the hidden field of our main form. then we can store the image file in that way.

else you can go for the ng-file-upload moduleng file upload

like image 32
Sahil Kashetwar Avatar answered Oct 13 '22 19:10

Sahil Kashetwar