Skip to content

Instantly share code, notes, and snippets.

@wh0th3h3llam1
Created November 14, 2022 19:34
Show Gist options
  • Save wh0th3h3llam1/8c6b765aa238b99b9eabab1b250199cc to your computer and use it in GitHub Desktop.
Save wh0th3h3llam1/8c6b765aa238b99b9eabab1b250199cc to your computer and use it in GitHub Desktop.
Form & Common Service to get Dirty Controls in Angular along with a custom field mapping (date -> string)
export interface IDirtyControl {
field: string,
type: string,
convertTo: string,
}
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { IDirtyControl } from '../common/interfaces/common.interface';
@Injectable({
providedIn: 'root'
})
export class CommonService {
constructor(private httpClient: HttpClient) {
}
convertCustomField(data: IDirtyControl, value: any) {
if (data.type == 'date') {
if (data.convertTo == 'string') {
return value.toJSON().split("T")[0]
} else if (data.convertTo == 'time') {
return value.toLocaleTimeString()
} else {
return value
}
}
else if (data.type == 'string') {
if (data.convertTo == 'date') {
return new Date(value)
}
}
}
}
import { Injectable } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { CommonService } from './common.service';
import { IDirtyControl } from '../common/interfaces/common.interface';
@Injectable({
providedIn: 'root'
})
export class FormService {
constructor(private commonService: CommonService) { }
getDirtyControls(formData: FormGroup, customMapping?: Array<IDirtyControl>) {
let customMappingFields = customMapping?.map(f => f.field)
let dirtyControls = {};
Object.keys(formData.controls).forEach((name) => {
const currentControl = formData.controls[name];
if (currentControl.dirty) {
if(customMappingFields?.includes(name)) {
let customField = customMapping?.find(m => m.field == name)
if(customField) {
let x = this.commonService.convertCustomField(customField, currentControl.value)
dirtyControls = { ...dirtyControls, [name]: x }
}
} else {
dirtyControls = { ...dirtyControls, [name]: currentControl.value }
}
}
});
return dirtyControls;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment