Skip to content

[Proposal] Initial / Original value API for AbstractControl #19747

@mkurcius

Description

@mkurcius

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question

Current behavior

Right now form controls do not remember its original value.

Expected behavior

FormControl, FormGroup. FormArray:

  • has property readonly original: any
    holding original value
  • has property readonly differ: boolean
    holding true if value differ, false otherwise
  • has property readonly valueDiffer: Observable<boolean>
    stream indicating if current value differs from original
  • has method revert() / rollback()
    changes value to original value
  • has method commit()
    set existing value as new original value

interface could looks like that:

interface EnhancedAbstractControl {
  readonly original: any;
  readonly differ: boolean;
  readonly valueDiffer: Observable<boolean>;
  
  commit(): void;
  rollback(options?: { onlySelf?: boolean, emitEvent?: boolean });
}

What is the motivation / use case for changing the behavior?

When creating form which updates current data it is also nice feature to allow user to revert changes for each individual field (instead of whole form) or set css class if value differ or show / hide other elements.

Sometimes also when user changes value from state A (original) -> B (end), some modal / warning need to be displayed now or when form is submitted or when value is changed. But for other values changes ex. A -> C or A -> D nothing happens. Validators are not candidates for this because value is valid.

With this new feature all this use cases will be easy to implement:

  • rollback / revert
<input [formControl]="control">
<button *ngIf="control.valueDiffer | async" (click)="control.rollback()">Undo</button>
  • css
<div [class.differ]="control.differ">
  <input [formControl]="control">
</div>
  • before submit
<form [formGroup]="form" (ngSubmit)="save()">
  <input formControlName="control">
</form>
save() {
  const control = this.form.get('control');
  if (control.original === "A" && control.value === "B") {
    //ex. show modal
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions