I have succeeded in creating multiple forms based on the value from the dropdown list, but I am not able to save the data from the input element into database. If my dropdown list displays the value 5, then 5 forms with the same number of input element will be shown and be ready for data entry. My problem is how to save these data from one or multiple forms textbox into database.
Service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Offspring } from './animal';
@Injectable({
providedIn: 'root'
})
export class AnimalService {
readonly Urloffspring = 'api/AnimalAPI'
constructor(private http:HttpClient) { }
formOffspring:Offspring = new Offspring();
formSubmitted: boolean = false;
postOffspring(formOffspring: any){
console.log(formOffspring);
return this.http.post<any>(this.Urloffspring, formOffspring);
}
}
**Component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { AnimalService } from '../animal.service';
@Component({
selector: 'app-fetch-data',
templateUrl: './fetch-data.component.html',
})
export class FetchDataComponent implements OnInit {
reactForm: FormGroup;
public forms: FormGroup[] = [];
public unitData: Object[] = [
{ Id: 'Form1', Form: '1' },
{ Id: 'Form2', Form: '2' },
{ Id: 'Form3', Form: '3' },
{ Id: 'Form4', Form: '4' },
{ Id: 'Form5', Form: '5' },
];
public val: string = "1";
public unitFields: Object = { text: 'Form', value: 'Form' };
public unitWaterMark: string = '';
ngOnInit(): void {
this.generateForms(1);
}
generateForms(count: number): void {
this.forms = [];
for (let i = 0; i < count; i++) {
this.forms.push(
this.fb.group({
Id: (0),
Animal: (null),
Tagno: (null),
})
)}
}
dropdownChange(args: any): void {
const selectedCount = parseInt(args.value, 10);
if (!isNaN(selectedCount)) {
this.generateForms(selectedCount);
}
}
onSubmit(): void {
if (this.forms.every(form => form.valid)) {
const allFormData = this.forms.map(form => form.value);
}
// ... validation code ...
this.service.postOffspring(this.forms).subscribe({
next: (response) => {
console.log('Forms saved successfully', response);
},
error: (error) => {
console.error('Error saving forms', error);
}
});
}
onSubmitAll() {
let allValid = true;
const allFormData = [];
this.forms.forEach((form, index) => {
if (form.valid) {
allFormData.push(form.value);
} else {
form.markAllAsTouched();
allValid = false;
}
});
if (allValid) {
// here can you get the all forms data and send it to backend using the angular service.
}
}
}
constructor(private fb: FormBuilder, private service: AnimalService ) {}
}
html
<div class="col-lg-12 control-section">
<div class="content-wrapper" style="max-width: 600px; margin: 0 auto;">
<ejs-dropdownlist
id="Unt"
[dataSource]="unitData"
type="text"
name="Unt"
[fields]="unitFields"
placeholder="Mark All"
(change)="dropdownChange($event)"
[query]="unitquery"
floatLabelType="Auto"
[value]="val"
>
</ejs-dropdownlist><br><br>
<div *ngFor="let form of forms; let i = index">
<form [id]="'formId' + i" [formGroup]="form" (ngSubmit)="onSubmit(form, i)" class="form-horizontal" novalidate>
<div class="form-title">
<span>Customer {{ i + 1 }}</span>
</div>
<div class="form-group">
<div class="e-float-input">
<input [id]="'Id' + i" formControlName="Id" />
<span class="e-float-line"></span>
<label [for]="'Id' + i" class="e-float-text"></label>
</div>
</div>
<div class="form-group">
<div class="e-float-input">
<input [id]="'Animal' + i" type="text" formControlName="Animal" />
<span class="e-float-line"></span>
<label [for]="'Animal' + i" class="e-float-text">Animal</label>
</div>
</div>
<div class="form-group">
<div class="e-float-input">
<input [id]="'Tagno' + i" type="text" formControlName="Tagno" />
<span class="e-float-line"></span>
<label [for]="'Tagno' + i" class="e-float-text">Tagno</label>
</div>
</div>
</form>
</div>
Backend
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Project1.Models;
using System.Data.SqlClient;
using System.Data;
using Microsoft.Extensions.Configuration;
namespace Project1.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AnimalAPIController : ControllerBase
{
private dbContext _context;
public AnimalAPIController(dbContext context, IConfiguration configuration)
{
_context = context;
}
[HttpPost]
public void Post([FromBody] Animaldb book)
{
_context.Animaldb.Add(book);
_context.SaveChanges();
}
}
}