加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:55:02 所属栏目:安全 来源:网络整理
导读:美好的一天, 我如何处理formControl中的输入类型文件?即时通讯使用反应形式,但当我得到我的表格的价值时,它会在我的 input type =“file”上返回空值. 解决方法 您需要编写自己的FileInputValueAccessor.这是 the plunker和代码: @Directive({ selector: '
美好的一天,

我如何处理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;
    });
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读