Reputation: 127
I have page in that i have 3 input fields and a grid with a add button to add data to the grid and a save button to save the whole data, here what i want to try is when a user add some data to the grid instead of making an API request it should save the data locally and when user click on the save button the whole data means grid data plus those 3 input field data should save in the database.
Paraent Model
export class ParentModel<GridModel> {
parentId: number;
totalDue: number;
totalAmount: number;
totalDiscount: number;
childModel: GridModel[];
constructor(init?: Partial<ParentModel<GridModel>>) {
Object.assign(this, init);
}
}
Child Model
export class GridModel {
parentId: number;
childId: number;
deliveyAmount: number;
taxAmount: number;
constructor(init?: Partial<GridModel>) {
Object.assign(this, init);
}
}
My Service to share the data between the models
@Injectable({
providedIn: 'root'
})
export class DataShareService{
private parentSubject: BehaviorSubject<ParentModel<GridModel[]>> = new BehaviorSubject<ParentModel<GridModel[]>>(null);
//Just in case if need to subscribe
paretnt= this.parentSubject.asObservable();
constructor() { }
setGridData(griData: GridModel[]) {
this.parentSubject.value.childModel = griData;
}
setParentData(parenData: ParentModel<GridModel[]>) {
this.parentSubject.next(parenData);
}
get parentData(): ParentModel<GridModel[]> {
return this.parentSubject.value;
}
}
Grid ts file
saveGridData() {
this.dataShareService.setGridData(this.gridForm.value);
}
Parent ts file
saveParentData() {
this.dataShareService.setParentData(this.parentForm.value);
}
But this not working as expected so, am i doing something wrong or is there any better way to do it
Upvotes: 1
Views: 1003
Reputation: 1931
This can be done with angular reactive forms. Google ‘dynamic reactive forms’. It’s a built in feature in angular. When clicking on the add button you can add a form group to the form and build it up before you submit it
That might also solve the challenge with the validation errors when you send a lot of data in one submit. Every form field will show its own error. Also a built in angular feature
Upvotes: 1