Open In App

Quote Generator App Using Angular

Last Updated : 02 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

4
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

3
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
2
create a service

Step 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.


Next Article

Similar Reads