角2 | 如何在FormControl中处理输入类型文件?

Jyd*_*Mah 5 forms angular

美好的一天,

我如何处理formControl中的输入类型文件?即时通讯使用反应形式,但当我得到我的形式的价值,它返回我的值的空值<input type="file">

Max*_*kyi 12

你需要自己写FileInputValueAccessor.这是plunker和代码:

@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() {  }
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以得到这样的更新:

@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;
    });
  }
}
Run Code Online (Sandbox Code Playgroud)