Hello my friends, welcome back to my blog. Today in this blog post, I am going to tell you, Angular 10 FullCalendar Add Event Demo Part 3 with Source Code.
Angular 10 came and if you are new then you must check below two links:
Friends now I proceed onwards and here is the working code snippet for Angular 10 FullCalendar Add Event Demo Part 3 with Source Code and please use carefully this to avoid the mistakes:
1. Firstly friends we need fresh angular 10 setup and for this we need to run below commands but if you already have angular 10 setup then you can avoid below commands. Secondly we should also have latest node version installed on our system:
npm install -g @angular/cli ng new angularaddevent //Create new Angular Project cd angularaddevent // Go inside the Angular Project Folder ng serve --open // Run and Open the Angular Project http://localhost:4200/ // Working Angular Project Url
2. Now friends, here we need to run below commands into our project terminal to install fullcalendar modules, bootstrap(for good looks), jquery to support bootstrap and sweetalert modules into our angular application:
npm install --save @fullcalendar/angular @fullcalendar/daygrid npm i @fullcalendar/interaction npm i bootstrap --save npm i jquery --save npm i --save sweetalert2 ng serve --o
3. Now friends, here we need to add below into our angular.json file to get modules styles and scripts:
... "styles": [ ... "node_modules/bootstrap/dist/css/bootstrap.min.css", "node_modules/sweetalert2/src/sweetalert2.scss" ], "scripts": [ ... "node_modules/jquery/dist/jquery.min.js", "node_modules/bootstrap/dist/js/bootstrap.min.js", "node_modules/sweetalert2/dist/sweetalert2.js" ] ...
4. Now add below code into your src/app/app.module.ts file:
... import { FullCalendarModule } from '@fullcalendar/angular'; import dayGridPlugin from '@fullcalendar/daygrid'; import interactionPlugin from '@fullcalendar/interaction'; import { ReactiveFormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; FullCalendarModule.registerPlugins([ dayGridPlugin, interactionPlugin ]); ... imports: [ ... FullCalendarModule, ReactiveFormsModule, HttpClientModule ], ...
5. Now add below code into your src/app/app.component.ts file:
... import { FormBuilder, FormGroup, Validators } from '@angular/forms'; declare let $: any; import { CalendarOptions } from '@fullcalendar/angular'; import { HttpClient } from '@angular/common/http'; import Swal from 'sweetalert2/dist/sweetalert2.js'; export class AppComponent { ... /* Add Event Form */ eventdate:string; successdata:any; addEventForm: FormGroup; submitted = false; //Add user form actions get f() { return this.addEventForm.controls; } onSubmit() { this.submitted = true; // stop here if form is invalid and reset the validations this.addEventForm.get('title').setValidators([Validators.required]); this.addEventForm.get('title').updateValueAndValidity(); if (this.addEventForm.invalid) { return; } //Form Submittion and send data via API if(this.submitted) { // Initialize Params Object var myFormData = new FormData(); // Begin assigning parameters myFormData.append('title', this.addEventForm.value.title); myFormData.append('startdate', this.eventdate); //post request return this.http.post('http://localhost/save.php/' , myFormData).subscribe((res: Response) => { $("#myModal").modal("hide"); this.successdata = res; if(this.successdata['data'] = "success") { //sweetalert message popup Swal.fire({ title: 'Hurray!!', text: this.addEventForm.value.title+" event has been added successfully", icon: 'success' }); } else { //sweetalert error message popup Swal.fire({ title: 'OPPSS!!', text: this.successdata['data'], icon: 'alert' }); } }); } } constructor(private formBuilder: FormBuilder, private http: HttpClient){} calendarOptions: CalendarOptions; ngOnInit() { this.calendarOptions = { initialView: 'dayGridMonth', dateClick: this.handleDateClick.bind(this), events: [ { title: 'event 1', date: '2020-11-05' }, { title: 'event 2', date: '2020-06-30' } ] }; //Add User form validations this.addEventForm = this.formBuilder.group({ title: ['', [Validators.required]] }); } //Show Modal with Forn on dayClick Event handleDateClick(arg) { $("#myModal").modal("show"); $(".modal-title, .eventstarttitle").text(""); $(".modal-title").text("Add Event at : "+arg.dateStr); $(".eventstarttitle").text(arg.dateStr); } //Hide Modal PopUp and clear the form validations hideForm(){ this.addEventForm.patchValue({ title : ""}); this.addEventForm.get('title').clearValidators(); this.addEventForm.get('title').updateValueAndValidity(); } }
6. Finally add below code into your src/app/app.component.html file:
<div class="container"> <div class="row"> <div class="col-sm-12"> <full-calendar [options]="calendarOptions"></full-calendar> </div> </div> </div> <!--Modal PopUp with Add Event Form--> <div class="modal" id="myModal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title align-center"></h4> <button type="button" class="close" (click)="hideForm()" data-dismiss="modal">×</button> </div> <div class="modal-body"> <form [formGroup]="addEventForm" (ngSubmit)="onSubmit()"> <div class="row"> <div class="col-sm-12"> <div class="form-group"> <label>Event Title</label> <input placeholder="Add Event Title" type="text" formControlName="title" class="titleinp form-control" [ngClass]="{ 'is-invalid': submitted && f.title.errors }" /> <div *ngIf="submitted && f.title.errors" class="invalid-feedback"> <div *ngIf="f.title.errors.required">Title is required</div> </div> </div> </div> <div class="col-sm-12"> <div class="form-group"> <label>Event Date:</label> <div class="form-control eventstarttitle"></div> </div> </div> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </div> </div> </div>
7. Now friends here is my php code snippet to save data and I added this code into my xampp/htdocs/save.php file:
//Please create events database inside phpmysql-admin and create events tabel and create id, title and startdate fields
<?php //add event //Database Connection $servername = "localhost"; $username = "root"; $password = ""; $dbname = "events"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } //Please create events database inside phpmysql admin and create events tabel and create id, title, startdate fields //Add Event if(isset($_POST['title'])) { $sql = "INSERT INTO events (title, startdate) VALUES ('".$_POST['title']."', '".$_POST['startdate']."')"; if (mysqli_query($conn,$sql)) { $data = array("data" => "success"); echo json_encode($data); } else { $data = array("data" => "Error: " . $sql . "<br>" . $conn->error); echo json_encode($data); } } ?>
Now we are done friends and please run ng serve command and if you have any kind of query then please do comment below.
Guys, in my next post, I will show you fetch saved events and show inside fullcalendar.
Note: Friends, I just tell the basic setup and things, you can change the code according to your requirements. For better understanding must watch video above.
I will appreciate that if you will tell your views for this post. Nothing matters if your views will be good or bad.
Jassa
Thanks
I love the efforts you have put in this, regards for all the great blog posts.
Thank you.
Hi, thanks for your work.
I tried your code but the date turns undefined.
What did I do wrong?
thx!
I will check it and update you thanks 🙂
Ok, I fixed the first problem by adding this piece of code I found in the documentation:
eventdate = formatDate(new Date(), {
month: ‘long’,
year: ‘numeric’,
day: ‘numeric’
});
It still doesn’t show the events on the calendar, eventhough they get stored in the db
Great.
Hello I tried your code but it does submit even the success and the error alert don’t show?
I will come with new updates with this:
For more angular updates please join this angular group
https://chat.whatsapp.com/HHvVqmqMIrd7kqpstaNAuL