/ngx-compare-object

An Angular Class tool to compare an initial object with another modified version of self.

Primary LanguageTypeScriptMIT LicenseMIT

NgxCompareObject npm version Build Status Support License

An Angular Class tool to compare an initial object with another modified version of itself.

Prerequisites

  • Angular: >=19.2.0

Usage

  1. Install via npm

npm i ngx-compare-object

  1. Import
import { NgxCompareObject } from 'ngx-compare-object';
  1. Usage example
<form [formGroup]="form">
   <div>
      <h2>Edit user</h2>
   </div>
   <div>
      <label>First name</label>
      <input type="text" formControlName="firtname">
   </div>
   <div>
      <label>Last name</label>
      <input type="text" formControlName="lastname">
   </div>
   <div>
      <label>Email</label>
      <input type="text" formControlName="email">
   </div>
   <div>
      <button type="button" [disabled]="!hasChanges()" (click)="restore()">Cancel</button>
      <button type="button"  [disabled]="!hasChanges()" (click)="submitUser()">Submit</button>
   </div>
</form>
private fb = inject(FormBuilder);
private route = inject(ActivatedRoute);

private co!: CompareObject;
form: FormGroup;
@Input() id: string;

ngOnInit(){
   if(this.id){
      this.getInfo(this.id);
   }
}

private getInfo(id: string){
   this.http.get('https://example.com/users/'+id)
   .subcribe((response)=>{
      this.initForm(response.user);
   })
}

private initForm(user: IUser){
   this.form = this.fb.group({
    firstname: [user.firstname, Validators.required],
    lastname: [user.lastname, Validators.required],
    email: [user.email, Validators.required]
   });

   const originalForm = this.form.value();

   this.co = new CompareObject(originalForm);
}

hasChanges(): boolean{
   if(!this.co) return;
   const form = this.form.value();
   return !this.co.isSame(form);
}
private restore(){
   this.form.reset(this.co.getOriginal());
}

submitUser(){
   if(this.hasChanges()){
      //do something
   }
}
cancelSubmit(){
   this.restore();
}