Quote Generator App Using Angular
Last Updated :
02 Sep, 2024
A Quote Generator App is a simple application that displays random quotes to users. It is a great project for practising Angular basics such as components, services, data and API integration.
Here we develop a simple Quote Generator App using Angular. This application can able to display a new Quote when you click on the Quote Generator button. In this article, we cover topics like how to create an Angular Project and how to integrate APIs.
Project Preview
Quote Generator App using Angular
Prerequisites
Approach For Quote Generator App
- Setting up a new Angular Project.
- Creating a component to display quotes.
- Creating a service to fetch quotes from an external API.
- Integrating Angular Bootstrap for UI components.
- Styling the App for clean look.
- Running and Testing the App.
The App will be built using Angular and leveraging as service to fetch quotes from an API and displaying them in a component. This project will be organized using a standalone app component and configuration.
Steps to Create Quote Generator App using Angular
Here First we create a Angular Application by using Angular commands after that we integrate a third party API to display a random quote to the user. For this follow below step by step process.
Step 1 : Install Angular CLI
If you don't have not installed Angular CLI install it using npm
npm install -g @angular/cli
Step 2 : Create a New Angular Project
Now create a new Angular Project by using below command. After that navigate to the project folder.
ng new quote-generator-app
cd quote-generator-app
Folder Structure
Project Folder
Dependencies
"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.12",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}
Step 3 : Install Required Modules
If you want to install any modules like Bootstrap or Any other CSS framework to develop the application with responsive behavior. Here we use Bootstrap Framework as CDN only.
index.html
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>QuoteGeneratorApp</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<app-root></app-root>
</body>
</html>
Step 4 : Create a Quote Service
Once Every thing is setup Now Its time to create a service for handling the quotes in this application for we use below command to create a app.service.ts.
ng g s --skip-tests quote-generator-app
create a serviceStep 5 : Implement Logic for Quotes Generate
Here we develop the logic for fetching a random quote and display in the user interface for this we need to update source code in different files. Below we provide that information for your reference.
app.component.html
In this file we write html code for creating user interface and display the fetched quotes from the third party API. Below we provide that source code for your reference.
HTML
//app.component.html
<div class="container p-5 bg-success mt-5">
<h2 class="text text-light">Random Quote Generator</h2>
<div class="quotes bg-light p-5 mt-3" style="border-radius: 15px">
<p *ngIf="quote === 'Loading...'">{{ quote }}</p>
<p *ngIf="quote === 'Failed to load quote. Please try again.'">
{{ quote }}
</p>
<p *ngIf="
quote !== 'Loading...' &&
quote !== 'Failed to load quote. Please try again.'
" style="font-weight: bold">
{{ quote }}
</p>
</div>
<button (click)="generateQuote($event)" type="button" class="btn btn-light mt-3">
Generate New Quote
</button>
</div>
app.component.ts
Once User interface is completed now Its time to create component logic for app.component.html file and we created a function called generateQuote() This function can able to fetch a random quote from the API.
JavaScript
//app.component.ts
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { QuoteGeneratorAppService } from './quote-generator-app.service';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule],
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
quote: string = 'Loading...';
constructor(private quoteService: QuoteGeneratorAppService) {
this.generateQuote();
}
generateQuote(event?: Event) {
if (event) {
event.preventDefault();
}
this.quote = 'Loading...';
this.quoteService.getRandomQuote().subscribe({
next: (quote: string) => {
this.quote = quote;
},
error: (err) => {
console.error('Error in generateQuote:', err);
this.quote = 'Failed to load quote. Please try again.';
}
});
}
}
app.config.ts
In this file we need configure the HttpClient For fetching and communicate with third party API for this we need configure the HttpClient in the app.config.ts file like below.
JavaScript
//app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient, withFetch } from '@angular/common/http';
import { provideClientHydration } from '@angular/platform-browser';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideClientHydration(),
provideHttpClient(withFetch())
]
};
quote-generator-app.service.ts: In this we are providing a sample quotes in json format.
JavaScript
//quote-generator-app.service.ts
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class QuoteGeneratorAppService {
private quotes = [
{
text: 'The only limit to our realization of tomorrow is our doubts of today.',
author: 'Franklin D. Roosevelt',
},
{ text: 'The purpose of our lives is to be happy.', author: 'Dalai Lama' },
{
text: "Life is what happens when you're busy making other plans.",
author: 'John Lennon',
},
{ text: 'Get busy living or get busy dying.', author: 'Stephen King' },
{
text: 'You only live once, but if you do it right, once is enough.',
author: 'Mae West',
},
{
text: 'Many of life’s failures are people who did not realize how
close they were to success when they gave up.',
author: 'Thomas A. Edison',
},
{
text: 'If you want to live a happy life, tie it to a goal, not to people or things.',
author: 'Albert Einstein',
},
{
text: 'Never let the fear of striking out keep you from playing the game.',
author: 'Babe Ruth',
},
{
text: 'Money and success don’t change people;
they merely amplify what is already there.',
author: 'Will Smith',
},
{
text: 'Your time is limited, so don’t waste it living someone else’s life.',
author: 'Steve Jobs',
},
{
text: 'Not how long, but how well you have lived is the main thing.',
author: 'Seneca',
},
{
text: 'If life were predictable it would cease to be life, and be without flavor.',
author: 'Eleanor Roosevelt',
},
{
text: 'The whole secret of a successful life is to find out what is
one’s destiny to do, and then do it.',
author: 'Henry Ford',
},
{
text: 'In order to write about life first you must live it.',
author: 'Ernest Hemingway',
},
{
text: 'The big lesson in life, baby, is never be scared of anyone or anything.',
author: 'Frank Sinatra',
},
];
constructor() { }
getRandomQuote(): Observable<string> {
const randomIndex = Math.floor(Math.random() * this.quotes.length);
const selectedQuote = this.quotes[randomIndex];
return of(`"${selectedQuote.text}" - ${selectedQuote.author}`);
}
}
Step 6 : Run the Application
Once Development is completed. Now run the Angular application by using Below command.
ng serve
Output
Once Application successfully run now check the output.
Similar Reads
Joke generator App Using Angular
Angular has become one of the most popular frameworks for building dynamic web applications. In this project, we build a simple yet entertaining Joke generator app using Angular. The app will fetch random jokes from a public API and display them to the user. This project will help us understand how
3 min read
Meme Generator App using Angular
Angular has become one of the, most popular frameworks for building dynamic web applications. In this project, we will build a simple yet entertaining Meme generator app using Angular. The app will fetch random memes from a public API and display them to the user. This project will help us understan
5 min read
Generate QR code using AngularJS
In this article, we will see how to generate and display QR codes in our Angular apps. A QR code is a matrix of black and white squares that can be read by a camera or a smartphone. A QR code can store information and URLs that make it easy to read for a bot or smartphone user. In a business scenari
3 min read
Quiz App using Angular
We will be creating a Quiz application using the Angular framework. This app will allow users to answer multiple-choice questions and view their results interactively. We'll use Angular Material for a polished UI and implement responsive design to ensure it looks great on all devices. The applicatio
5 min read
News App Using Angular
We will be developing a News Application using the Angular framework. This interactive app will allow users to search for news articles and filter them by category. With a clean and responsive design, it will dynamically display articles, providing an engaging and user-friendly experience. The app w
9 min read
Calculator App Using Angular
This Calculator app will provide basic arithmetic functionalities such as addition, subtraction, multiplication, and division, with a clean and modern UI. It will be fully responsive and interactive, ensuring a great user experience across different devices. This project is suitable for both beginne
4 min read
Movie App Using Angular
We will be creating a Movie Search Engine using Angular. This application allows users to search for movies by entering keywords and fetching and displaying a list of movie results in card format. The search engine initially loads a default set of movies to showcase the functionality. Through this p
5 min read
Event Calender using Angular
In this article, we will walk through the steps to create a dynamic Event Calendar using Angular 17 standalone components. This calendar will allow users to add events to specific dates and view them interactively. We will utilize Angular's powerful features and best practices to build a clean and e
6 min read
Expense Tracker Using Angular
Managing expenses efficiently is very important for personal finance. In this article, we'll walk through creating a simple yet effective Expense Tracker application using Angular 17. This project will showcase Angular's powerful features and provide a hands-on example of how to manage financial dat
7 min read
Angular Authentication Using Route Guards
In Angular, implementing authentication is important for securing routes and controlling access to different parts of the application based on user authentication status. Angular provides a powerful feature called Route Guards, and among them, the Auth Guard is used to control navigation based on th
12 min read