角度-查看父组件中的变量更改

时间:2018-07-06 20:28:42

标签: javascript angular typescript callback

基本上,我有一个作为父组件的表单。此表单由一个子组件组成。

为了禁用按钮,我使用函数 isDatasetFilesValid()检查变量(datasetList [i] .fileValid)。 该变量在子组件中更改。

但是,当我使用papaparse解析文件时,此更改是在回调中完成的,并且因为它是在回调中完成的,因此父级看不到它。我知道,因为如果我在回调之外更改变量,则按钮是可用。

选中此变量以确保已选择文件。

因此,我尝试添加“ detectChanges()”,但是它不起作用。

父组件:

   export class ExperimentCreateComponent implements OnInit {

     datasetList: any = [{ fileValid: false }];

     isDatasetFilesValid() {
       let index = this.datasetList.findIndex(function(item, i) {
       return item.fileValid == false;
       });
      let test = index === -1 ? true : false;
      console.log("Dataset", index + " -> " + test);
      return test;
      }
    }

父HTML:

<div class="jumbotron">
  <div class="container">
    <div class="row">
      <div class="col-sm-8 offset-sm-2">

        <form name="form" (ngSubmit)="f.form.valid" #f="ngForm" novalidate>


              <app-creation-dataset [datasetList]="datasetList"></app-creation-dataset>

                <button mat-button color="primary" type="submit" [disabled]="!isDatasetFilesValid()" (click)="createExperiment()">Submit</button>


        </form>
      </div>
    </div>
  </div>
</div>

子组件:

export class CreationDatasetComponent implements OnInit {
  @Input() datasetList: any = [{ fileValid: false }];
  fileSelected: File;


  constructor(private papa: Papa, private cd: ChangeDetectorRef) {}

  ngOnInit() {}

  onChange(files: FileList, index: number, dom: any) {
    // Option to parse the file with papaparse
    let options = {
      header: true,
      error: (err, file) => {
        this.datasetList[index].fileValid = false;
        alert(
          "Unable to parse CSV file, please verify the file can be accessed and try again. Error reason was: " +
            err.code
        );
        return;
      },
      complete: (results, file) => {
        console.log("Parsed:", results, file);
        let filename = file.name;

        // Add the dataset to the datasetList
        this.datasetList[index].headers = results.meta.fields;
        this.datasetList[index].values = results.data;
        this.datasetList[index].filename = filename;
        this.datasetList[index].is_metadata = false;
        this.datasetList[index].fileValid = true;
        this.cd.detectChanges();
      }
    };
    this.fileSelected = files[0]; // Get the file
    // Call the function to parse the file, option is the callback
    this.papa.parse(this.fileSelected, options);
  }
}

子HTML:

<div *ngFor="let dataset of datasetList; let index = index">
  <div id="datasetFiles">
    <h6>Select the type of dataset and browse the files:</h6>
    <div class="container">
      <div class="row justify-content-between">
        <div class="col-6 d-flex align-items-center">
          <input id="file" #file (change)="onChange(file.files, index, $event.currentTarget)" type="file">
        </div>
      </div>
    </div>
  </div>
</div>
<div>

1 个答案:

答案 0 :(得分:0)

由于当更改位于回调外部而不是内部时,父级会观察到您的更改,因此上下文可能有问题。

尝试一下:

  onChange(files: FileList, index: number, dom: any) {

    var that = this; // outer context

    // Option to parse the file with papaparse
    let options = {
      header: true,
      error: (err, file) => {
        this.datasetList[index].fileValid = false;
        alert(
          "Unable to parse CSV file, please verify the file can be accessed and try again. Error reason was: " +
            err.code
        );
        return;
      },
      complete: (results, file) => {
        console.log("Parsed:", results, file);
        let filename = file.name;

        // Add the dataset to the datasetList
        this.datasetList[index].headers = results.meta.fields;
        this.datasetList[index].values = results.data;
        this.datasetList[index].filename = filename;
        this.datasetList[index].is_metadata = false;
        that.datasetList[index].fileValid = true; // changed this to that
        this.cd.detectChanges();
      }
    };
    this.fileSelected = files[0]; // Get the file
    // Call the function to parse the file, option is the callback
    this.papa.parse(this.fileSelected, options);
  }