Angular reactive form valueChanges函数用于检测和存储仅更改的字段

时间:2018-03-15 22:22:53

标签: angular angular-reactive-forms

提交表单后,我只想捕获已更改字段的值。

使用表单上的valueChanges函数捕获表单的每个字段,它不能像我在下面的代码中尝试的那样遍历数组。

我不确定'之前和之后的其他方式。可以比较和存储表单的值,只存储已更改的字段。

export class JobEditComponent implements OnInit {
jobNumber: any;
jobs: any[];
jobToEdit: Job;
job: any;
brands: Brand[];
jobForm: FormGroup;
bsConfig: Partial<BsDatepickerConfig>;
isFormReady: any;
jobId: number;
existingValues: string[] = [];
changedValues: string[] = [];


constructor(private route: ActivatedRoute,
  private jobService: JobService,
  private fb: FormBuilder,
  private router: Router,
  private alertify: AlertifyService) { }

ngOnInit() {
  this.route.params.subscribe(params => {
    this.jobNumber = +params['id'];
    });

    this.jobService.getJobToEdit().subscribe((jobs: Job[]) => {
      this.jobs = jobs;
    }, error => { console.log('error');
    }, () => {
      this.jobToEdit = this.jobs.find(j => j.id === this.jobNumber);
      this.editJobForm();
      this.onChanges();
    });

    this.getBrands();

    this.bsConfig = {
      containerClass: 'theme-blue'
    };
  }

onChanges(): void {
  this.jobForm.valueChanges.subscribe(val => {
    if (this.existingValues != null) {
      this.existingValues = val;
    }
  });
}


editJobForm() {
  this.jobForm = this.fb.group({
    jobNumber: [this.jobToEdit.jobNumber, Validators.required],
    item: [this.jobToEdit.item, Validators.required],
    status: [this.jobToEdit.status, Validators.required],
    orderedBy: [this.jobToEdit.orderedBy, Validators.required],
    orderDate: [this.jobToEdit.orderDate, Validators.required],
    quantity: [this.jobToEdit.quantity, Validators.required],
    unitPrice: [this.jobToEdit.unitPrice, Validators.required],
    lineValue: [this.jobToEdit.lineValue, Validators.required],
    dpAp: [this.jobToEdit.dpAp, Validators.required],
    eta: [this.jobToEdit.eta, Validators.required],
    detailStatus: [this.jobToEdit.detailStatus, Validators.required],
    comments: [this.jobToEdit.comments, null]
  }, ); this.isFormReady = true;
}

updateJob() {
  this.alertify.confirm('Are you sure you want save changes?', () => {
  this.jobId = this.jobToEdit.id;
  this.jobToEdit = Object.assign({}, this.jobForm.value);
  this.jobService.editJob(this.jobToEdit, this.jobId).subscribe(() => {
    this.alertify.success('Update successful');
    **for (let i = 0; i < this.existingValues.length; i++) {
      if (this.jobToEdit[i] !== this.existingValues[i]) {
         this.changedValues[i] = this.jobToEdit[i];
      }
    }**
    console.log(this.changedValues);
  }, error => {
    this.alertify.error(error);
  }, () => {
    this.router.navigate(['/home']);
  });
});
}

}

2 个答案:

答案 0 :(得分:0)

试试这个循环:

// declare changedValues as key -> val object (not array)
changedValues: { [key: string]: any } = {};

Object.keys(this.existingValues).forEach(i => {
  if (this.jobToEdit[i] !== this.existingValues[i]) {
     this.changedValues[i] = this.jobToEdit[i];
  }
}

<强>更新

使用@Alex提出的for (key in object)语法的相同循环:

for (let key in this.existingValues) {
  if (this.jobToEdit[key] !== this.existingValues[key]) {
     this.changedValues[key] = this.jobToEdit[key];
  }
}

答案 1 :(得分:0)

您可以检查提交时的值,而不是使用valueChanges,因此如果您的表单如下所示:

constructor(private fb: FormBuilder) {
  this.myForm = this.fb.group({
    field1: [this.values.field1],
    field2: [this.values.field2],
    field3: [this.values.field3]
  })
}

您可以提交检查属性的值并查看它们是否匹配:

// 'values' is 'myForm.values'
onSubmit(values) {
  let changed = {};
  for (let ctrl in values) {
    if(values[ctrl] !== this.values[ctrl]) {
      changed[ctrl] = values[ctrl];
    }
  }
  console.log(changed);
}

这是一个

StackBlitz