|
| 1 | +# NgxCompareObject [](https://badge.fury.io/js/ngx-cam-shoot) [](https://app.travis-ci.com/github/rzodev/ngx-compare-object) []() [](https://github.com/RzoDev/ngx-compare-object/blob/main/LICENSE.md) |
| 2 | + |
| 3 | +An Angular Class tool to compare an initial object with another modified version of itself. |
| 4 | + |
| 5 | +## Usage |
| 6 | + |
| 7 | +1. Install via npm |
| 8 | + |
| 9 | +`npm i ngx-compare-object` |
| 10 | + |
| 11 | +2. Import |
| 12 | + |
| 13 | +```typescript |
| 14 | +import { NgxCompareObject } from 'ngx-compare-object'; |
| 15 | +``` |
| 16 | + |
| 17 | +3. Usage example |
| 18 | + |
| 19 | +```html |
| 20 | +<form [formGroup]="form"> |
| 21 | + <div> |
| 22 | + <h2>Edit user</h2> |
| 23 | + </div> |
| 24 | + <div> |
| 25 | + <label>First name</label> |
| 26 | + <input type="text" formControlName="firtname"> |
| 27 | + </div> |
| 28 | + <div> |
| 29 | + <label>Last name</label> |
| 30 | + <input type="text" formControlName="lastname"> |
| 31 | + </div> |
| 32 | + <div> |
| 33 | + <label>Email</label> |
| 34 | + <input type="text" formControlName="email"> |
| 35 | + </div> |
| 36 | + <div> |
| 37 | + <button type="button" [disabled]="!hasChanges()" (click)="restore()">Cancel</button> |
| 38 | + <button type="button" [disabled]="!hasChanges()" (click)="submitUser()">Submit</button> |
| 39 | + </div> |
| 40 | +</form> |
| 41 | +``` |
| 42 | + |
| 43 | +```typescript |
| 44 | +private fb = inject(FormBuilder); |
| 45 | +private route = inject(ActivatedRoute); |
| 46 | + |
| 47 | +private co!: CompareObject; |
| 48 | +form: FormGroup; |
| 49 | +private @Input() id: string; |
| 50 | + |
| 51 | +ngOnInit(){ |
| 52 | + if(this.id){ |
| 53 | + this.getInfo(this.id); |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +private getInfo(id: string){ |
| 58 | + this.http.get('https://example.com/users/'+id) |
| 59 | + .subcribe((response)=>{ |
| 60 | + this.initForm(response.user); |
| 61 | + }) |
| 62 | +} |
| 63 | + |
| 64 | +private initForm(user: IUser){ |
| 65 | + this.form = this.fb.group({ |
| 66 | + firstname: [user.firstname, Validators.required], |
| 67 | + lastname: [user.lastname, Validators.required], |
| 68 | + email: [user.email, Validators.required] |
| 69 | + }); |
| 70 | + |
| 71 | + const originalForm = this.form.value(); |
| 72 | + |
| 73 | + this.co = new CompareObject(originalForm); |
| 74 | +} |
| 75 | + |
| 76 | +hasChanges(): boolean{ |
| 77 | + const form = this.form.value(); |
| 78 | + return !this.co.isSame(form); |
| 79 | +} |
| 80 | +private restore(){ |
| 81 | + this.form.reset(this.co.getOriginal()); |
| 82 | +} |
| 83 | + |
| 84 | +submitUser(){ |
| 85 | + if(this.hasChanges()){ |
| 86 | + //do something |
| 87 | + } |
| 88 | +} |
| 89 | +cancelSubmit(){ |
| 90 | + this.restore(); |
| 91 | +} |
| 92 | +``` |
0 commit comments