Angular 6中嵌套FormArray中的patchValue

时间:2019-02-21 05:07:20

标签: angular angular6

我想在嵌套的FormArray中修补单个值。修补值是文件的base64encode。并且,此补丁应该发生在onFileChange事件上。但是,以某种方式,它无法正常工作并显示错误,patchValue不是函数。 以下是我用来修补值的代码行:this.uploader.controls['sections']['value'][this.valueofitem].patchValue({afterImage: btoa(binaryString)});
并将其写入文件读取器功能内。请参见下面的代码。

Component.ts文件

import {Component, OnDestroy, OnInit, ElementRef, ViewChild} from '@angular/core';
import {Router, ActivatedRoute} from '@angular/router';
import {FileuploaderService} from '../fileuploader.service';
import {CountryService} from '../../country/country.service';
import {ServicelocationsService} from '../../servicelocations/servicelocations.service';
import {CategoriesService} from '../../categories/categories.service';
import {FormBuilder, FormGroup, Validators, FormArray, FormControl} from '@angular/forms';

@Component({
  selector: 'app-services-cu',
  templateUrl: '../pages/fileuploader-cu.component.html'
})

export class FileuploaderCuComponent implements OnInit {
  uploader: FormGroup;
  profilepicSize = 0;
  valueofitem = 0;

  constructor() {
  }

  ngOnInit() {
    this.uploader = new FormGroup({
      sections: new FormArray([
        this.initSection(),
      ]),
    });
  }

  initSection() {
    return new FormGroup({
      beforeImage: new FormControl(''),
      afterImage: new FormControl('')
    });
  }

  addSection() {
    const control = <FormArray> this.uploader.get('sections');
    control.push(this.initSection());
  }

  getSections(form) {
    return form.controls.sections.controls;
  }

  removeSection(i) {
    const control = <FormArray> this.uploader.get('sections');
    control.removeAt(i);
  }

  onSubmit(form) {
    // console.log(this.uploader);
    // this.uploader.controls['sections']['value'][this.valueofitem].afterImage = 'Test';
    // console.log(this.uploader.controls['sections']['value']);
    const reader = new FileReader();
    for (const images of this.uploader.controls['sections']['value']) {
      console.log(images.afterImage);
    }
  }

  onFileChange(event, i) {
    const reader = new FileReader();
    if (event.target.files && event.target.files.length) {
      const [file] = event.target.files;
      this.profilepicSize = file.size;
      this.valueofitem = i;
      reader.readAsBinaryString(file);
      reader.onload = this._handleReaderLoaded.bind(this);
    }

  }
  _handleReaderLoaded(readerEvt) {
    const binaryString = readerEvt.target.result;
    // this.uploader.patchValue({
    //   beforeImage: btoa(binaryString)
    // });
    const control = <FormArray> this.uploader.get('sections');
    // console.log(this.uploader.controls['sections']['value'][this.valueofitem].afterImage);
   this.uploader.controls['sections']['value'][this.valueofitem].patchValue({afterImage: btoa(binaryString)});
  }
}

Component.html文件

    <div class="row">
  <div class="col-md-12 col-sm-12 col-xs-12">
    <div class="x_panel">
      <form [formGroup]="uploader" novalidate (ngSubmit)="onSubmit(uploader)">
        <!--- Section -->
        <div class="row">
          <div formArrayName="sections">
            <div class="row" *ngFor="let section of getSections(uploader); let i = index">
              <div class="col-md-12 col-sm-12 col-xs-12">
                <div [formGroupName]="i">
                  <!---Uploader Section -->
                  <div class="col-sm-12 col-md-4">
                    <div class="input-group margin-bottom-sm">
                      <label>Before:</label>
                      <input type="file" formControlName="beforeImage" accept=".jpeg, .jpg, .png" class="form-control">
                      <span style="font-size:12px;">(Formats:jpeg, jpg, png Size: 1MB)</span>
                    </div>
                  </div>
                  <div class="col-sm-12 col-md-4">
                    <div class="input-group margin-bottom-sm">
                      <label>After:</label>
                      <input type="file" formControlName="afterImage" accept=".jpeg, .jpg, .png" class="form-control"
                             (change)="onFileChange($event,i)">
                      <span style="font-size:12px;">(Formats:jpeg, jpg, png Size: 1MB)</span>
                    </div>
                  </div>
                  <!---End of Uploader Section -->
                </div>
                <br>
                <button type="button" (click)="addSection()" class="btn btn-info btn-sm">Add More</button>
                <button type="button" class="btn btn-danger btn-sm" *ngIf="getSections(uploader).length > 1"
                        (click)="removeSection(i)">Remove Section
                </button>
              </div>
            </div>
          </div>
        </div>
        <!-- End Section -->
        <hr>
        <div class="row">
          <div class="col-md-6 col-md-offset-6">
            <div *ngIf="errors" class="alert alert-danger">{{errors.error|json}}</div>
            <!--<a class="btn btn-warning pull-right" [routerLink]="'/controlpanel/users/'"> Cancel</a>-->
            <a class="btn btn-danger pull-right" [routerLink]="'/company/services/'"><i class="fa fa-close"></i>
              Cancel</a>
            <button class="btn btn-primary pull-right" [disabled]="loading" type="submit">{{ actionType }}
            </button>
          </div>
        </div>
      </form>
      <pre> {{uploader.value | json}} </pre>
    </div>
  </div>
</div>

0 个答案:

没有答案
相关问题