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

后端 未结 2 1722
孤街浪徒
孤街浪徒 2021-02-06 10:06

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

2条回答
  •  不要未来只要你来
    2021-02-06 10:40

    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: `
          

    Hello {{name}}

    File path is: {{path}}

    ` }) export class AppComponent { name = 'Angular'; path = ''; ctrl = new FormControl(''); ngOnInit() { this.ctrl.valueChanges.subscribe((v) => { this.path = v; }); } }

提交回复
热议问题