如何在Angular 4的FormGroup中的键中添加值

时间:2018-08-10 21:31:26

标签: angular typescript

我想提交一个包含文件的表格。 因此,我使用ng2-file-upload npm进行文件上传

component.html是-

<input type="file" ng2FileSelect [uploader]="uploader" (onFileSelected)="onFileSelected($event)">

而我的component.ts是-

public uploader: FileUploader = new FileUploader({});

  uploadForm: FormGroup;

  constructor(
    private formBuilder: FormBuilder,
    private userService: UserServiceService
  ) {
  }

  ngOnInit() {

    this.uploadForm = this.formBuilder.group({
      branch         : ['cs', Validators.required],
      document       : [null, Validators.required],
      semester       : ['3', Validators.required],
    });


  }


  //////////// File Converted into base64/////////////////


  onFileSelected(event: EventEmitter<File[]>) {
    const file: File = event[0];

    readBase64(file)
      .then(function(data) {
         console.log(data);

        this.uploadForm.patchValue({  // Showing error -- Potentially invalid reference access to a class field via 'this.' 
          document: data
        });
      });

  }

我正在onFileSelected()函数中生成文件的base64,然后要将该base64添加到document中的formGroup键中。但是当我尝试使用this.uploadForm.patchValue()时,它显示错误

Potentially invalid reference access to a class field via 'this.'

我只想在data的{​​{1}}键中添加document

1 个答案:

答案 0 :(得分:0)

任何一个

  .then(function(data) {
     this.whateva
    }.bind(this)); //here is the trick

  .then(data=> {//here is the trick
     this.whateva
    }); 

我没有阅读其余的代码。