Share and Learn To Write Code!

Programming articles, which help you to build your application. If something you are stuck to code and complete the program, just find here your question-related articles.

Share with   

Design student simple database using slick carousel implementation in angular 7 with firebase.

Here we are design simple firebase database for storing student information and showing list of data in table. And for more attractive displying images in pages we are implementing slick carousel in angular 7.
slick carousel   angular   angular 7   firebase   angular 2+  

Introduction


Here we are design simple firebase database for storing student information and firebase storage for storing images and showing list of data in table. And for more attractive displying images in pages we are implementing slick carousel in angular 7.


Prerequisite


1) Angular 7, If you do not know how to install angular in your system please check this article install Angular

2) Firebase, If you do not know how to install firebase in angular cli please follow the article.

3) HTML/Bootstrap


In this article, we will create a simple Angular 7 application in a step-by-step manner from scratch to perform the CRUD operations on student information using Firebase and implement slick-carousel for image slider.


Follow the below steps


1) Create Angular App

ng new student_info

This will create student_info angular 7 project.


2) Open this app in visual code or any other which is used by you.


3) Install all prerequisites packages for angular app

npm install firebase @angular/fire ngx-slick-carousel slick-carousel jquery bootstrap --save

In this project we need firebase, ngx slick carousel and jquery bootstrap dependancy packages. This command will install all the prerequisites packages for angular app.


4) Go to src > angular.json file to register slick carousel, jquery and bootstrap in style and js see below code.

// angular.json

"styles": [
	 "src/styles.scss",
	 "node_modules/slick-carousel/slick/slick.scss",
	 "node_modules/slick-carousel/slick/slick-theme.scss",
	 "node_modules/bootstrap/dist/css/bootstrap.css"
],

"scripts": [
	 "node_modules/jquery/dist/jquery.min.js",
	 "node_modules/slick-carousel/slick/slick.min.js"
]


5) Make sure to create firebase account and project for this Student Information App. If you dont know how to create firebase account and project or app please follow this article click here.


6) After successfully create firebase app get credential from this created app and paste to our angular app. For paste this code to our angular app go to environment directory and paste to both environment files i.e.

// src > environments > environment.ts

export const environment = {
	  production: false,
	  firebase: {
	    apiKey: "YOUR_API_KEY",
	    authDomain: "YOUR_AUTH_DOMAIN",
	    databaseURL: "YOUR_DATABASE_URL",
	    projectId: "YOUR_PROJECT_ID",
	    storageBucket: "",
	    messagingSenderId: "YOUR_MESSAGING_SENDER_ID"
	 }
};

// src > environments > environment.prod.ts

export const environment = {
	  production: true,
	  firebase: {
	    apiKey: "YOUR_API_KEY",
	    authDomain: "YOUR_AUTH_DOMAIN",
	    databaseURL: "YOUR_DATABASE_URL",
	    projectId: "YOUR_PROJECT_ID",
	    storageBucket: "",
	    messagingSenderId: "YOUR_MESSAGING_SENDER_ID"
	 }
};


7)Register Firebase, Slick Carousel, and form modules to app module ts file

// src > app > app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { SlickCarouselModule } from 'ngx-slick-carousel';
import { SlickCarouselComponent } from './other-components/slick-carousel/slick-carousel.component';
import { AngularFireModule } from '@angular/fire';
import { environment } from '../environments/environment';
import { NavbarComponent } from './other-components/navbar/navbar.component';
import { StudentListComponent } from './other-components/student-list/student-list.component';
import { NewStudentComponent } from './other-components/new-student/new-student.component';
import { FormsModule } from '@angular/forms';
import { AngularFireDatabaseModule } from '@angular/fire/database';
import { AngularFireStorageModule } from '@angular/fire/storage';

@NgModule({
  declarations: [
  	AppComponent,
  	SlickCarouselComponent,
  	NavbarComponent,
  	StudentListComponent,
  	NewStudentComponent
  ],
  imports: [
  	BrowserModule,
  	AppRoutingModule,
  	SlickCarouselModule,
  	FormsModule,
  	AngularFireModule.initializeApp(environment.firebase,'techved-task'),
  	AngularFireDatabaseModule,
  	AngularFireStorageModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }


8) Create angular components for Navbar, Display list of student in table format, Display slick carousel and create and edit student information. We can use shortcut keywords for generating component, module or services etc.

//Create Navbar
ng g c other-components/navbar

//Create Student Create or edit component
ng g c other-components/new-student

//Display student component
ng g c other-components/student-list

//Displaying slick carousel
ng g c other-components/slick-carousel

//create student service
ng g s other-components/students

//create student model add new student.ts file in src > app > other-components


9) Design simple navbar for student information app

// src > app > other-components > navbar > navbar.component.html

<div class="d-flex flex-column flex-md-row align-items-center p-3 px-md-4 mb-3 bg-white border-bottom box-shadow">
	<h5 class="my-0 mr-md-auto font-weight-normal">Student Dashboard</h5>
	<nav class="my-2 my-md-0 mr-md-3">
	  <a class="p-2 text-dark" [routerLink]="[ '/home' ]">Home</a>
	  <a class="p-2 text-dark" [routerLink]="[ '/student/new-student' ]">Add-New Student</a>
	</nav>
</div>


10) Now we write all CRUD operations on student service file for create, read, update and delete student information.

// src > app > other-components > student-list > student-list.component.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase, AngularFireList, AngularFireObject } from '@angular/fire/database';
import { AngularFireStorage } from '@angular/fire/storage';
import { Student } from './student';
import { finalize } from 'rxjs/operators';
	
@Injectable({
	providedIn: 'root'
})

export class StudentsService {
	student_list: AngularFireList<Student[]>;
	student: AngularFireObject<Student>;
	
    constructor(private db: AngularFireDatabase,private storage: AngularFireStorage,) { 
	    this.getStudentList();
    }
	
    getStudentList() {
	    this.student_list = this.db.list("student-list");
	    return this.student_list;
	}

	createStudentData(student: Student, file: File){
	    let key = this.db.list('student-list').push(student).key;
	    //Upload File to firebase Storage
	    const path = `student-list` + `/` + key + `/` + student.firstname;
	    const storageRef = this.storage.ref(path);
	    const uploadTask = this.storage.upload(path,file);
	    // Done Uploading and changes into student-list database to add ImageURL
	    uploadTask.snapshotChanges().pipe(
	      finalize(() => {
	        storageRef.getDownloadURL().subscribe(data => { 
	          student.imageUrl = data;
	          this.db.object('student-list/'+key).set(student);
	        });
	      })
	    ).subscribe();
	}

	getStudentById(key) {
		this.student = this.db.object('student-list/' + key);
		return this.student;
	}

	updateStudentData(id, student,file: File) { 
	    this.db.object('/student-list/' + id).update(student);
	    const path = `student-list` + `/` + id + `/` + student.firstname;
	    const storageRef = this.storage.ref(path);
	    const uploadTask = this.storage.upload(path,file);
	    // Done Uploading and changes into student-list database to add ImageURL
	    uploadTask.snapshotChanges().pipe(
	      finalize(() => {
	        storageRef.getDownloadURL().subscribe(data => { 
	          student.imageUrl = data;
	          this.db.object('student-list/'+id).set(student);
	        });
	      })
	    ).subscribe();
	}

	deleteStudentRecord(key: string) {
		this.student_list.remove(key);
	}  
}


11) Create Student Model

// src > app > other-component > student.ts
export class Student {
	 $key?: string;
	 firstname: string;
	 lastname: string;
	 dob: string;
	 email: string;
	 phone:number;
	 high_edu: string;
	 university : string;
	 collage : string;
	 gender : string;
	 male : boolean;
	 female : boolean;
	 imageUrl: string;
	 category : string;
	 constructor(){
	     this.male = false;
	     this.female = false;
	 }
}



12) Create New or Edit Student Html Page and operation of html page in component.ts file

// src > app > other-components > new-student > new-student.component.html

<div class="jumbotron text-center">
	  <div class="text-center">
	    <h4>To add new student form</h4>
	  </div>
	</div>
	<div class="container">
	  <div class="row">
	    <div class="col-md-7">
	      <form class="needs-validation" #addStudentForm="ngForm" (ngSubmit)="create(addStudentForm)">
	        <div class="form-group">
	          <label>Student First Name</label>
	          <input #lastname="ngModel" [(ngModel)]="student_list.firstname" name="firstname" id="firstname" type="text"
	            class="form-control" required>
	        </div>
	        <div class="form-group">
	          <label>Student Last Name</label>
	          <div class="input-group">
	            <input #lastname="ngModel" [(ngModel)]="student_list.lastname" name="lastname" id="lastname" type="text"
	              class="form-control" required>
	          </div>
	        </div>
	        <div class="form-group">
	          <label>Gender</label>
	          <div class="row" style="margin-left: 5px">
	              <div class="custom-control custom-radio col-md-2">
	                  <input id="male" type="radio" [(ngModel)]="student_list.gender" class="custom-control-input" value="Male" name="gender">
	                  <label class="custom-control-label" for="male">Male</label>
	              </div>
	                <div class="custom-control custom-radio col-md-1">
	                  <input id="female" type="radio" [(ngModel)]="student_list.gender" class="custom-control-input" value="Female" name="gender">
	                  <label class="custom-control-label" for="female">Female</label>
	                </div>
	          </div>
	        </div>
	        <div class="form-group">
	          <label>Date of Birth</label>
	          <div class="input-group">
	            <input #dob="ngModel" [(ngModel)]="student_list.dob" name="dob" id="dob" type="date"
	              class="form-control" required>
	          </div>
	        </div>
	        <div class="form-group">
	          <label>University</label>
	          <select #university="ngModel" [(ngModel)]="student_list.university" name="university" id="university"
	            class="form-control" required>
	            <option>Savitribai Phule Pune University</option>
	            <option>Mumbai University</option>
	            <option>Coimbaator Univarsity</option>
	            <option>Delhi Univarsity</option>
	          </select>
	        </div>
	        <div class="form-group">
	          <label>Highest Education</label>
	          <div class="input-group">
	            <input #high_edu="ngModel" [(ngModel)]="student_list.high_edu" name="high_edu" id="high_edu" type="text"
	              class="form-control" required>
	          </div>
	        </div>
	        <div class="form-group">
	          <label>College Name</label>
	          <div class="input-group">
	            <input #collage="ngModel" [(ngModel)]="student_list.collage" name="collage" id="collage"
	              type="text" class="form-control" required>
	          </div>
	        </div>
	        <div class="form-group">
	          <label>Email ID</label>
	          <div class="input-group">
	            <input #email="ngModel" [(ngModel)]="student_list.email" name="email" id="email"
	              type="email" class="form-control">
	          </div>
	        </div>
	        <div class="form-group">
	          <label>Phone</label>
	          <input #phone="ngModel" [(ngModel)]="student_list.phone" name="phone" id="phone" type="tel"
	            class="form-control" required>
	        </div>
	        <div class="form-group">
	          <label> Select Student Image</label>
	          <br>
	          <input name="file" [(ngModel)]="student_list.imageUrl" type="file" id="file" (change)="handleFileInput($event.target.files)">
	        </div>
	        <button class="btn btn-primary btn-lg btn-block" type="submit">Add Student</button>
	      </form>
	    </div>
	    <!-- This is showing Image when selecting image file -->
	    <div class="col-md-4" style="padding-top: 50px;">
	      <div class="card" *ngIf="student_list.imageUrl">
	        <div class="card card-cascade wider">
	          <div class="view overlay hm-white-slight">
	            <img [src]="student_list.imageUrl" class="img-fluid" alt="" width="360px" height="640px">
	          </div>
	        </div>
	      </div>
	    </div>
	</div>
</div>
<br> <br>


13) New or Edit Student Html Page operation in component.ts file

// src > app > other-components > new-student > new-student.component.ts

import { Component, OnInit } from '@angular/core';
import { StudentsService } from '../students.service';
import { Router, ActivatedRoute } from '@angular/router';
import { Student } from '../student';
import { NgForm } from '@angular/forms';
import { take } from 'rxjs/operators';
@Component({
	selector: 'app-new-student',
	templateUrl: './new-student.component.html',
	styleUrls: ['./new-student.component.scss']
})
export class NewStudentComponent {
	student_list: Student;
	fileToUpload: File = null;
	sub: any;
	constructor(private studentService: StudentsService,private route: ActivatedRoute,private router: Router) {
	    this.student_list = new Student();
	    this.sub = this.route.snapshot.paramMap.get('id');
	    if (this.sub) this.studentService.getStudentById(this.sub).valueChanges().pipe(take(1)).subscribe(data => this.student_list = data);
	}
    handleFileInput(file: FileList) {
	    this.fileToUpload = file.item(0);
	    var reader = new FileReader();
	    reader.onload = (event: any) => {
	      this.student_list.imageUrl = event.target.result;
	    }
	    reader.readAsDataURL(this.fileToUpload);
	}
	create(studentForm: NgForm) {
	    let image: File;
	    image = this.fileToUpload;
	    if (this.sub) this.studentService.updateStudentData(this.sub, studentForm.value, image);
  	    else this.studentService.createStudentData(studentForm.value, image);
  	    alert('Student Add Successfully !!');
  	    this.router.navigateByUrl('/student-list');
  	}
}


14) Design Slick Carousel Image slider Html page

// src > app > other-components > slick-carousel > slick-carousel.component.html

<div class="jumbotron text-center">
	  <h1>Welcome to Student Dashboard</h1><br>
	  <h3>Example of slick-carousel</h3>
	</div>
	<div class="container">
	    <ngx-slick-carousel class="carousel" #slickModal="slick-carousel" [config]="slideConfig">
	        <div ngxSlickItem *ngFor="let slide of student_list" class="slide" id="slide">
	          <img src="{{ slide.imageUrl }}" alt="" height="300px" width="90%" class="imagecenter">
	          <p>{{slide.firstname}} {{slide.lastname}}</p>
	        </div>
	   </ngx-slick-carousel> 
   </div>
</div>


15) Code for working ngx-slick -carousel ts file.

// src > app > other-components > slick-carousel > slick-carousel.component.html

import { Component, OnInit } from '@angular/core';
import { Student } from '../student';
import { StudentsService } from '../students.service';

@Component({
	selector: 'app-slick-carousel',
	templateUrl: './slick-carousel.component.html',
	styleUrls: ['./slick-carousel.component.scss']
})
export class SlickCarouselComponent implements OnInit {
	slideConfig = {"slidesToShow": 4, "slidesToScroll": 1, "autoplay": true, autoplaySpeed: 1000};
	student_list: Student[];

	constructor(private studentService : StudentsService) { 
	    this.student_list = [];
	}
	
    ngOnInit() {
	    this.getAllStudents();
    }
	
    getAllStudents() {
	    const x = this.studentService.getStudentList();
	    x.snapshotChanges().subscribe(
	      Response => {
	        this.student_list = [];
	        Response.forEach(element => {
	          const y = element.payload.toJSON();
	          y["$key"] = element.key;
	          this.student_list.push(y as Student);
	        });
	      }
	    );
	}
}


16) Displaying Student list in table format html file and also image slider using slick carousel selector

// src > app > other-components > student-list > student-list.component.html

<app-slick-carousel></app-slick-carousel>
<br>
<div class="jumbotron text-center">
	    <h1>Welcome to Student Portal</h1>
	</div>
	<div class="table-responsive">
	    <table class="table table-bordered">
	        <thead>
	            <tr>
	                <th>Id</th>
	                <th>Student Photo</th>
	                <th>Student Name</th>
	                <th>Gender</th>
	                <th>Email ID</th>
	                <th>Phone Number</th>
	                <th>DOB</th>
	                <th>Highest Education</th>
	                <th>College Name</th>
	                <th>Univarsity</th>
	                <th>Action</th>
	            </tr>
	        </thead>
	        <tbody>
	            <tr *ngFor="let item of student_list; let i=index">
	                <th>{{i}}</th>
	                <td><img [src]="item.imageUrl" height=100px></td>
	                <td>{{item.firstname}}&nbsp;{{item.lastname}}</td>
	                <td>{{item.gender}}</td>
	                <td>{{item.email}}</td>
	                <td>{{item.phone}}</td>
	                <td>{{item.dob}}</td>
	                <td>{{item.high_edu}}</td>
	                <td>{{item.collage}}</td>
	                <td>{{item.university}}</td>
	                <td style="text-align : center">
	                    <button type="button" class="btn btn-success" [routerLink]="['/student/',item.$key]">Edit</button>
	                    <button type="button" class="btn btn-danger" (click)="removeStudent(item.$key)">Delete</button>
	                </td>
	                <!-- Modal -->
	            </tr>
	       </tbody>
	  </table>
</div>


17) Fetch all the student information from firebase and disaplay in the student table adding code in compont.ts file and also add the delete specific student record from list usign firebase service.

// src > app > other-components > student-list > student-list.component.ts

import { Component, OnInit } from '@angular/core';
import { Student } from '../student';
import { StudentsService } from '../students.service';
import { ActivatedRoute } from '@angular/router';
@Component({
	selector: 'app-student-list',
	templateUrl: './student-list.component.html',
	styleUrls: ['./student-list.component.scss']
})
export class StudentListComponent implements OnInit {
	student_list: Student[];
	student : Student;
	constructor(private studentService : StudentsService,private route: ActivatedRoute,) { 
	    this.student_list = [];
   }

   ngOnInit() {
  	    this.getAllStudents();
   }
  	
   getAllStudents() {
  	   const x = this.studentService.getStudentList();
  	   x.snapshotChanges().subscribe(
  	      Response => {
  	        this.student_list = [];
  	        Response.forEach(element => {
  	          const y = element.payload.toJSON();
  	          y["$key"] = element.key;
  	          this.student_list.push(y as Student);
  	        });
  	      }
  	   );
  	}
  	
  removeStudent(key: string) {
    if (confirm('Are you sure want to delete this student record?')) {
    	this.studentService.deleteStudentRecord(key);
    }
  }
}


18) Finally change in app component html file

// src > app > app.component.html
<app-navbar></app-navbar>
<router-outlet></router-outlet>


19) Last step is set routing for html pages

 // src > app > app-routing.module.ts
 
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SlickCarouselComponent } from './other-components/slick-carousel/slick-carousel.component';
import { StudentListComponent } from './other-components/student-list/student-list.component';
import { NewStudentComponent } from './other-components/new-student/new-student.component';
	
const routes: Routes = [
	  { path: '', redirectTo: '/home', pathMatch: 'full' },
	  { path: 'home', component: StudentListComponent },
	  { path: 'student/new-student', component: NewStudentComponent },
	  { path: 'student/:id', component: NewStudentComponent },
];	
@NgModule({
	  imports: [RouterModule.forRoot(routes)],
	  exports: [RouterModule]
})8 

export class AppRoutingModule { }


Successfully Done Student Information CRUD App in Angular 7.

To see live demo click here

And If you want demo project click here for github link.

0replies
Leave a reply
43
Registerd Users
84
Total Subscribers
59
Total Articles
30612
Total Views