形式 – Angular 2 |如何在FormControl中处理输入类型文件?

前端之家收集整理的这篇文章主要介绍了形式 – Angular 2 |如何在FormControl中处理输入类型文件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
美好的一天,

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

解决方法

您需要编写自己的FileInputValueAccessor.这是 the 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() {  }
}

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

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

猜你在找的Angularjs相关文章