Implementing reactive forms in my Angular project allowed me to create a simple form for adding employee work hours and breaks. The challenge I encountered was the inability to bind data from break controls.
In the .ts file
export class AddAppointmentFormComponent implements OnInit{
addAppointmentForm!: FormGroup
constructor(private _fb:FormBuilder, private _wfmService:WFMService) {}
ngOnInit(): void {
this.addAppointmentForm = this._fb.group({
typeOfDayId :['',Validators.required],
appointMentDate: ['', Validators.required],
from: ['', Validators.required],
to: ['', Validators.required],
breaks: this._fb.array([
]),
})
}
get breaks(){
return this.addAppointmentForm.get('breaks') as FormArray;
}
addBreak(){
this.breaks.push(this._fb.group({
from: ['', Validators.required],
to: ['', Validators.required],
}))
}
removeBreak(i:any){
this.breaks.removeAt(i);
}
}
In the .html file
<div mat-dialog-content [align]="'start'">
<h4 mat-dialog-title style="text-align: center;">Add New Appointment</h4>
{{ addAppointmentForm.value | json }}
<form [formGroup]="addAppointmentForm">
<!-- HTML code skipped for brevity -->
</form>
<div class="btn__actions">
<button class="btn btn-danger" mat-dialog-close>Close</button>
<button style="margin-left:10px ;" class="btn btn-primary">Create</button>
</div>
</div>
The desired output is:
{{ addAppointmentForm.value | json }}
"breaks": [ { "from": "10:00", "to": "10:30" }, { "from": "14:00", "to": "14:30" } ] }