{"id":4071,"date":"2023-11-04T23:14:02","date_gmt":"2023-11-04T23:14:02","guid":{"rendered":"http:\/\/localhost:10003\/how-to-build-a-quiz-app-with-angular-and-firebase\/"},"modified":"2023-11-05T05:48:22","modified_gmt":"2023-11-05T05:48:22","slug":"how-to-build-a-quiz-app-with-angular-and-firebase","status":"publish","type":"post","link":"http:\/\/localhost:10003\/how-to-build-a-quiz-app-with-angular-and-firebase\/","title":{"rendered":"How to Build a Quiz App with Angular and Firebase"},"content":{"rendered":"
In this tutorial, we will learn how to build a quiz app using Angular and Firebase. The app will allow users to take quizzes, view their scores, and create and manage quizzes as well. We will be using Angular for the front-end and Firebase as our backend, which will handle user authentication and data storage.<\/p>\n
To follow along with this tutorial, you will need to have the following installed on your machine:<\/p>\n
Let’s start by setting up our Angular project. Open your terminal and run the following command to install Angular CLI globally:<\/p>\n
npm install -g @angular\/cli\n<\/code><\/pre>\nNext, create a new Angular project by running the following command:<\/p>\n
ng new quiz-app\n<\/code><\/pre>\nNavigate to the project directory:<\/p>\n
cd quiz-app\n<\/code><\/pre>\nStep 2: Set Up Firebase Project<\/h2>\n
Now, let’s set up our Firebase project. Go to the Firebase console<\/a> and create a new project. Give it a name and select your preferred region.<\/p>\nOnce your project is created, click on the “Authentication” tab in the sidebar, and enable the “Email\/Password” sign-in method.<\/p>\n
Next, click on the “Database” tab in the sidebar, and create a new Cloud Firestore database. Choose the “Start in test mode” option for now.<\/p>\n
After creating the database, click on the “Rules” tab and replace the existing rules with the following:<\/p>\n
rules_version = '2';\nservice cloud.firestore {\n match \/databases\/{database}\/documents {\n match \/{document=**} {\n allow read, write: if request.auth != null;\n }\n }\n}\n<\/code><\/pre>\nStep 3: Create the Quiz and Authentication Services<\/h2>\n
Let’s create two services: quiz.service.ts<\/code> for managing quizzes and auth.service.ts<\/code> for authentication.<\/p>\nCreate a new directory called services<\/code> under the src\/app<\/code> directory, and inside it, create quiz.service.ts<\/code> and auth.service.ts<\/code> files.<\/p>\nIn quiz.service.ts<\/code>, add the following code:<\/p>\nimport { Injectable } from '@angular\/core';\nimport { AngularFirestore, AngularFirestoreCollection } from '@angular\/fire\/firestore';\nimport { Observable } from 'rxjs';\n\n@Injectable({\n providedIn: 'root'\n})\nexport class QuizService {\n private quizCollection: AngularFirestoreCollection<any>;\n\n constructor(private firestore: AngularFirestore) {\n this.quizCollection = this.firestore.collection<any>('quizzes');\n }\n\n createQuiz(quiz: any): Promise<any> {\n return this.quizCollection.add(quiz);\n }\n\n getQuizzes(): Observable<any[]> {\n return this.quizCollection.valueChanges({ idField: 'id' });\n }\n}\n<\/code><\/pre>\nIn auth.service.ts<\/code>, add the following code:<\/p>\nimport { Injectable } from '@angular\/core';\nimport { AngularFireAuth } from '@angular\/fire\/auth';\nimport { Observable } from 'rxjs';\n\n@Injectable({\n providedIn: 'root'\n})\nexport class AuthService {\n user$: Observable<firebase.User | null>;\n\n constructor(public auth: AngularFireAuth) {\n this.user$ = this.auth.authState;\n }\n\n signUp(email: string, password: string): Promise<any> {\n return this.auth.createUserWithEmailAndPassword(email, password);\n }\n\n signIn(email: string, password: string): Promise<any> {\n return this.auth.signInWithEmailAndPassword(email, password);\n }\n\n signOut(): Promise<void> {\n return this.auth.signOut();\n }\n}\n<\/code><\/pre>\nEnsure that you have installed the angular\/fire<\/code> package by running the following command:<\/p>\nng add @angular\/fire\n<\/code><\/pre>\nStep 4: Create the Quiz List Component<\/h2>\n
Now, let’s create the quiz list component which will display a list of available quizzes.<\/p>\n
Generate a new component called quiz-list<\/code> using the Angular CLI:<\/p>\nng generate component quiz-list\n<\/code><\/pre>\nIn the quiz-list.component.ts<\/code> file, add the following code:<\/p>\nimport { Component, OnInit } from '@angular\/core';\nimport { Observable } from 'rxjs';\nimport { QuizService } from '..\/services\/quiz.service';\n\n@Component({\n selector: 'app-quiz-list',\n templateUrl: '.\/quiz-list.component.html',\n styleUrls: ['.\/quiz-list.component.css']\n})\nexport class QuizListComponent implements OnInit {\n quizzes$: Observable<any[]>;\n\n constructor(private quizService: QuizService) { }\n\n ngOnInit() {\n this.quizzes$ = this.quizService.getQuizzes();\n }\n}\n<\/code><\/pre>\nIn the quiz-list.component.html<\/code> file, add the following code:<\/p>\n<div *ngFor=\"let quiz of quizzes$ | async\">\n <h2>{{ quiz.name }}<\/h2>\n <p>{{ quiz.description }}<\/p>\n<\/div>\n<\/code><\/pre>\nStep 5: Create the Quiz Detail Component<\/h2>\n
Let’s create the quiz detail component which will display the details of a specific quiz.<\/p>\n
Generate a new component called quiz-detail<\/code> using the Angular CLI:<\/p>\nng generate component quiz-detail\n<\/code><\/pre>\nIn the quiz-detail.component.ts<\/code> file, add the following code:<\/p>\nimport { Component, OnInit } from '@angular\/core';\n\n@Component({\n selector: 'app-quiz-detail',\n templateUrl: '.\/quiz-detail.component.html',\n styleUrls: ['.\/quiz-detail.component.css']\n})\nexport class QuizDetailComponent implements OnInit {\n\n constructor() { }\n\n ngOnInit() {\n }\n\n}\n<\/code><\/pre>\nIn the quiz-detail.component.html<\/code> file, add the following code:<\/p>\n<h2>Quiz Detail<\/h2>\n<\/code><\/pre>\nStep 6: Set Up Routing<\/h2>\n
Now, let’s set up the routing for our app. Open the app-routing.module.ts<\/code> file and replace the existing code with the following:<\/p>\nimport { NgModule } from '@angular\/core';\nimport { Routes, RouterModule } from '@angular\/router';\nimport { QuizListComponent } from '.\/quiz-list\/quiz-list.component';\nimport { QuizDetailComponent } from '.\/quiz-detail\/quiz-detail.component';\n\nconst routes: Routes = [\n { path: '', redirectTo: '\/quizzes', pathMatch: 'full' },\n { path: 'quizzes', component: QuizListComponent },\n { path: 'quiz\/:id', component: QuizDetailComponent }\n];\n\n@NgModule({\n imports: [RouterModule.forRoot(routes)],\n exports: [RouterModule]\n})\nexport class AppRoutingModule { }\n<\/code><\/pre>\nStep 7: Update App Component and HTML<\/h2>\n
Open the app.component.ts<\/code> file and replace the existing code with the following:<\/p>\nimport { Component } from '@angular\/core';\nimport { AuthService } from '.\/services\/auth.service';\n\n@Component({\n selector: 'app-root',\n templateUrl: '.\/app.component.html',\n styleUrls: ['.\/app.component.css']\n})\nexport class AppComponent {\n constructor(public authService: AuthService) { }\n}\n<\/code><\/pre>\nOpen the app.component.html<\/code> file and replace the existing code with the following:<\/p>\n<nav class=\"navbar navbar-expand-lg navbar-light bg-light\">\n <a class=\"navbar-brand\" href=\"\/\">Quiz App<\/a>\n\n <ul class=\"navbar-nav ml-auto\">\n <li class=\"nav-item\" *ngIf=\"!authService.user$ | async\">\n <a class=\"nav-link\" routerLink=\"\/signin\">Sign in<\/a>\n <\/li>\n <li class=\"nav-item\" *ngIf=\"!authService.user$ | async\">\n <a class=\"nav-link\" routerLink=\"\/signup\">Sign up<\/a>\n <\/li>\n <li class=\"nav-item\" *ngIf=\"authService.user$ | async\">\n <a class=\"nav-link\" (click)=\"authService.signOut()\">Sign out<\/a>\n <\/li>\n <\/ul>\n<\/nav>\n\n<div class=\"container mt-4\">\n <router-outlet><\/router-outlet>\n<\/div>\n<\/code><\/pre>\nStep 8: Create the Signin and Signup Components<\/h2>\n
Let’s create the signin and signup components which will handle user authentication.<\/p>\n
Generate a new component called signin<\/code> using the Angular CLI:<\/p>\nng generate component signin\n<\/code><\/pre>\nGenerate a new component called signup<\/code> using the Angular CLI:<\/p>\nng generate component signup\n<\/code><\/pre>\nAdd the routing for the signin<\/code> and signup<\/code> components in the app-routing.module.ts<\/code> file:<\/p>\nimport { NgModule } from '@angular\/core';\nimport { Routes, RouterModule } from '@angular\/router';\nimport { QuizListComponent } from '.\/quiz-list\/quiz-list.component';\nimport { QuizDetailComponent } from '.\/quiz-detail\/quiz-detail.component';\nimport { SigninComponent } from '.\/signin\/signin.component';\nimport { SignupComponent } from '.\/signup\/signup.component';\n\nconst routes: Routes = [\n { path: '', redirectTo: '\/quizzes', pathMatch: 'full' },\n { path: 'quizzes', component: QuizListComponent },\n { path: 'quiz\/:id', component: QuizDetailComponent },\n { path: 'signin', component: SigninComponent },\n { path: 'signup', component: SignupComponent }\n];\n\n@NgModule({\n imports: [RouterModule.forRoot(routes)],\n exports: [RouterModule]\n})\nexport class AppRoutingModule { }\n<\/code><\/pre>\nIn the signin.component.ts<\/code> file, add the following code:<\/p>\nimport { Component, OnInit } from '@angular\/core';\nimport { Router } from '@angular\/router';\nimport { AuthService } from '..\/services\/auth.service';\n\n@Component({\n selector: 'app-signin',\n templateUrl: '.\/signin.component.html',\n styleUrls: ['.\/signin.component.css']\n})\nexport class SigninComponent implements OnInit {\n email: string;\n password: string;\n error: string;\n\n constructor(private authService: AuthService, private router: Router) { }\n\n ngOnInit() {\n }\n\n signIn() {\n this.authService.signIn(this.email, this.password)\n .then(() => this.router.navigate(['\/']))\n .catch(error => this.error = error.message);\n }\n}\n<\/code><\/pre>\nIn the signin.component.html<\/code> file, add the following code:<\/p>\n<h2>Sign In<\/h2>\n\n<div class=\"form-group\">\n <label for=\"email\">Email<\/label>\n <input type=\"email\" class=\"form-control\" id=\"email\" [(ngModel)]=\"email\">\n<\/div>\n\n<div class=\"form-group\">\n <label for=\"password\">Password<\/label>\n <input type=\"password\" class=\"form-control\" id=\"password\" [(ngModel)]=\"password\">\n<\/div>\n\n<div class=\"form-group\">\n <button class=\"btn btn-primary\" (click)=\"signIn()\">Sign In<\/button>\n<\/div>\n\n<p *ngIf=\"error\" class=\"text-danger\">{{ error }}<\/p>\n<\/code><\/pre>\nIn the signup.component.ts<\/code> file, add the following code:<\/p>\nimport { Component, OnInit } from '@angular\/core';\nimport { Router } from '@angular\/router';\nimport { AuthService } from '..\/services\/auth.service';\n\n@Component({\n selector: 'app-signup',\n templateUrl: '.\/signup.component.html',\n styleUrls: ['.\/signup.component.css']\n})\nexport class SignupComponent implements OnInit {\n email: string;\n password: string;\n error: string;\n\n constructor(private authService: AuthService, private router: Router) { }\n\n ngOnInit() {\n }\n\n signUp() {\n this.authService.signUp(this.email, this.password)\n .then(() => this.router.navigate(['\/']))\n .catch(error => this.error = error.message);\n }\n}\n<\/code><\/pre>\nIn the signup.component.html<\/code> file, add the following code:<\/p>\n<h2>Sign Up<\/h2>\n\n<div class=\"form-group\">\n <label for=\"email\">Email<\/label>\n <input type=\"email\" class=\"form-control\" id=\"email\" [(ngModel)]=\"email\">\n<\/div>\n\n<div class=\"form-group\">\n <label for=\"password\">Password<\/label>\n <input type=\"password\" class=\"form-control\" id=\"password\" [(ngModel)]=\"password\">\n<\/div>\n\n<div class=\"form-group\">\n <button class=\"btn btn-primary\" (click)=\"signUp()\">Sign Up<\/button>\n<\/div>\n\n<p *ngIf=\"error\" class=\"text-danger\">{{ error }}<\/p>\n<\/code><\/pre>\nStep 9: Deploy Firebase Hosting<\/h2>\n
Now that we have completed the app, let’s deploy it using Firebase Hosting.<\/p>\n
First, install the Firebase CLI by running the following command:<\/p>\n
npm install -g firebase-tools\n<\/code><\/pre>\nThen, log in to Firebase by running the following command and following the authentication prompts:<\/p>\n
firebase login\n<\/code><\/pre>\nNext, initialize Firebase in your project directory by running the following command:<\/p>\n
firebase init\n<\/code><\/pre>\nSelect “Hosting” as the Firebase CLI feature, and choose the Firebase project you created earlier. For the public directory, enter “dist\/quiz-app” (or the directory where the build artifacts are located).<\/p>\n
After the initialization is complete, build the Angular app by running the following command:<\/p>\n
ng build --prod\n<\/code><\/pre>\nFinally, deploy the app to Firebase Hosting by running the following command:<\/p>\n
firebase deploy\n<\/code><\/pre>\nCongratulations! Your quiz app is now deployed and accessible using the provided Firebase Hosting URL.<\/p>\n
Conclusion<\/h2>\n
In this tutorial, we learned how to build a quiz app using Angular and Firebase. We set up the Angular project, created services for managing quizzes and authentication, and built components for the quiz list, quiz detail, signin, and signup functionality. We also deployed our app using Firebase Hosting, making it available to users on the web.<\/p>\n
Feel free to enhance the app by adding more features, such as the ability for users to answer quizzes and view their scores. You can also explore other Angular and Firebase features, such as Firestore transactions for handling quiz submissions and Cloud Functions for server-side logic. Happy coding!<\/p>\n","protected":false},"excerpt":{"rendered":"
In this tutorial, we will learn how to build a quiz app using Angular and Firebase. The app will allow users to take quizzes, view their scores, and create and manage quizzes as well. We will be using Angular for the front-end and Firebase as our backend, which will handle Continue Reading<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_import_markdown_pro_load_document_selector":0,"_import_markdown_pro_submit_text_textarea":"","footnotes":""},"categories":[1],"tags":[1157,1161,357,10,1159,1160,1162,34,275,1158],"yoast_head":"\nHow to Build a Quiz App with Angular and Firebase - Pantherax Blogs<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n