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

Good afternoon,

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

+4
source share
2 answers

You need to write your own FileInputValueAccessor. Here is the plunker and 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 can receive such updates:

@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;
    });
  }
}
+8
source

angular. , , . <input type=file> , , , base64code, . .

else ng ng

0

Source: https://habr.com/ru/post/1681940/


All Articles