Create A New Angular Project From Scratch - Build an Angular Weather App From Scratch [With Source Code]

Sameer Saini May 16, 2022
Create A New Angular Project From Scratch - Build an Angular Weather App From Scratch [With Source Code]

Angular is a very popular Javascript framework for front end development and we all know that. Along with React and Vue, Angular stands tall when it comes to choosing the framework to create reactive front end websites.

In this article, we will create an Angular project from scratch

We will use Angular 13 to create this Angular project and we will be building a very fancy Angular weather application which tells you the weather of a location.

This Angular project will have a search functionality in which the user can type in the location for which they want to search the weather for.

With a slick UI, this Angular tutorial can be the perfect way to start learning Angular by creating a real world project.

 

 

Prerequisites

If you want to follow this tutorial, you will need to have:

  • Prior knowledge of TypeScript.
  • A development machine with Node installed. Node is requred to install Angular CLI. To install Angular CLI, please visit this official page from google, Install Angular CLI

Once you have installed NodeJs and Angular CLI it's time to create your Angular 13 project.

 

 

1 - Create Angular 13 Project Using Angular CLI

In this step, we will use Angular CLI to initialize our Angular project.

Go to your terminal or command prompt window and browse to the location you want to create your Angular 13 project.

Then run the following commands:

ng new WeatherApp

The CLI will prompt you and ask the following questions:

  • Weather you would like to add Angular routing? Enter 'Yes'
  • It will then ask which stylesheet format you would like to use? Choose CSS

After selecting the options, Angular CLI will take some time and generate the required files for you.

It will also install all the required npm packages and also setup routing for our project.

ow, go to the project's root folder and run the local development server using these commands:

cd WeatherApp ng serve

We will also open the created project inside visual studio code.

 

 

2. Cleaning Our Angular Application

The next thing we will do is to clean the existing app.component.html file and remove any un-used HTML and CSS from it.

We will remove everything from this file but will keep the last line i.e. router-outlet.

After the cleanup, your app.component.html should look like this:

 

 

3. Adding Angular Forms and HttpClient To App Module

In this step, we will add HttpClient and FormsModule to our project.

We will open the app.module.ts file under the location src/app/app.module.ts and update the existing code to the following:

import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import {HttpClientModule} from '@angular/common/http'; import { FormsModule } from '@angular/forms'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }

 

 

4. Creating UI Structure For Our App

Let's create the HTML for our Angular weather application project and we will come to the app.component.html file.

We will create a container div element in which will have 2 sections.

The upper data section will hold the name of the location and the temperature.

The lower data section will be like a more information section holding other related details like minimum temperature, maximum temperature etc.

The code for the app.component.html will look like below:

{{ weatherData.name }}
{{ weatherData.main.temp | number: '1.0-0'}}°C
More Information
min
{{weatherData.main.temp_min | number: '1.0-0'}}°C
max
{{weatherData.main.temp_max | number: '1.0-0'}}°C
humidity
{{weatherData.main.humidity}}%
wind
{{weatherData.wind.speed}} km/h

 

 

5. Styling Our UI Components

It's time to make things beautiful by adding some CSS.

Please add the below CSS or modify it as per your liking. I am going to add this CSS to the style.css file in the /src/ location.

:root { --blue-1: #3C429E; --blue-2: #4C52AD; --yellow-1: #FAC742; --white: #FFF; --grey-1: #EDEDED; --shadow-dark: rgba(0,0,0,0.3); --shadow-light: rgba(255,255,255,0.1); } * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: Verdana, Geneva, Tahoma, sans-serif; font-size: 16px; width: 100%; height: 100vh; background-color: var(--blue-1); display: flex; justify-content: center; align-items: center; } .container { width: 400px; height: 80vh; background-color: var(--blue-2); border-radius: 20px; box-shadow: 10px 10px 10px var(--shadow-dark); } .upper-data { position: relative; overflow: hidden; width: 100%; height: 50%; border-top-left-radius: 20px; border-top-right-radius: 20px; } .lower-data { position: relative; overflow: hidden; width: 100%; height: 50%; border-bottom-left-radius: 20px; border-bottom-right-radius: 20px; padding: 1em; display: flex; flex-direction: column; } .upper-data img { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } .weather-data { position: relative; z-index: 1; width: 100%; height: 100%; background-color: var(--shadow-dark); display: flex; flex-direction: column; align-items: center; justify-content: center; } .location { color: var(--white); text-align: center; font-size: 1.2em; } .temperature { color: var(--white); font-size: 4em; text-align: center; font-weight: 900; } .more-info-label { color: var(--white); } .more-info-container { flex: 1; background-color: var(--shadow-light); border-bottom-left-radius: 20px; border-bottom-right-radius: 20px; margin-top: 1em; display: flex; flex-direction: row; flex-wrap: wrap; } .info-block { width: 50%; display: flex; flex-direction: row; } .info-block-label { width: 50%; display: flex; flex-direction: column; justify-content: center; align-items: center; } .info-block-label img { width: 1.5em; } .info-block-label span { color: var(--white); font-size: 0.8em; } .info-block-value { width: 50%; display: flex; justify-content: flex-start; align-items: center; color: var(--white); } .search { margin-bottom: 1em; text-align: center; } .search input { background-color: var(--shadow-light); outline: none; border: none; border-radius: 20px; padding: 1em; color: var(--grey-1); font-size: 0.8em; text-align: center; }

 

 

6. Register To RapidApi Service To Get Weather API Data

In this app we are going to link our Angular project to talk to an external API using RapidAPI.

RapidAPI is an API hub which hosts a lot of free and paid public APIs that we can use.

We are going to use the weather API from RapidAPI.

To use an API, sign up to rapidapi.com

After signing up, you can search and subscribe to the API.

We will use Open Weather Map API from RapidAPI.

 

 

7. Create Angular Service To Call API

In this step, we will create an Angular service using the Angular CLI.

We will create a services folder inside the app folder and using the terminal, create the angular service.

ng g s weather

After creating the service, we will paste the below code to get the data from the RapidAPI weather API.

The values for environment.weatherApiBaseUrl, environment.XRapidAPIHostHeaderValue, environment.XRapidAPIKeyHeaderValue needs to be replaced with the values you get in your dashboard for RapidAPI.com

import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { environment } from 'src/environments/environment'; import { WeatherData } from '../models/weather.model'; @Injectable({ providedIn: 'root' }) export class WeatherService { constructor(private http: HttpClient) { } getWeatherData(cityName: string): Observable { return this.http.get(environment.weatherApiBaseUrl, { headers: new HttpHeaders() .set(environment.XRapidAPIHostHeaderName, environment.XRapidAPIHostHeaderValue) .set(environment.XRapidAPIKeyHeaderName, environment.XRapidAPIKeyHeaderValue), params: new HttpParams() .set('q', cityName) .set('units', 'metric') .set('mode', 'json') }) } }

 

 

8. Replace Values In Environment.ts

Now, we will add values in the environment.ts file and replace the values from the values you got from your rapidapi.com dashboard.

// This file can be replaced during build by using the `fileReplacements` array. // `ng build` replaces `environment.ts` with `environment.prod.ts`. // The list of file replacements can be found in `angular.json`. export const environment = { production: false, weatherApiBaseUrl: 'https://community-open-weather-map.p.rapidapi.com/weather', XRapidAPIHostHeaderName: 'X-RapidAPI-Host', XRapidAPIHostHeaderValue: 'community-open-weather-map.p.rapidapi.com', XRapidAPIKeyHeaderName: 'X-RapidAPI-Key', XRapidAPIKeyHeaderValue: 'YOUR_KEY' }; /* * For easier debugging in development mode, you can import the following file * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. * * This import should be commented out in production mode because it will have a negative impact * on performance if an error is thrown. */ // import 'zone.js/plugins/zone-error'; // Included with Angular CLI.

 

 

9. Connect App.Component.ts to Service

It's now time to call the service that we created from the app.component.ts file and connect our app to the API.

Use the code below to connect the app to the Angular service

import { Component, OnInit } from '@angular/core'; import { WeatherData } from './models/weather.model'; import { WeatherService } from './services/weather.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { constructor(private weatherService: WeatherService) { } cityName: string = 'Wellington'; weatherData?: WeatherData; ngOnInit(): void { this.getWeatherData(this.cityName); this.cityName = ''; } onSubmit() { this.getWeatherData(this.cityName); this.cityName = ''; } private getWeatherData(cityName: string) { this.weatherService.getWeatherData(cityName) .subscribe({ next: (response) => { this.weatherData = response; console.log(response); } }); } }

 

 

10. Angular Weather App Project - Video Tutorial