Implementing Weather Chart as Standalone Component in Angular

Vikesh Mittal
6 min readSep 7, 2024

--

Standalone components in web development emerged as a response to the growing complexity of modern web applications and the desire to improve developer productivity, scalability, and maintainability. The idea of standalone components evolved as web applications became more feature-rich, requiring modularization and better organization. The shift toward component-driven development can be traced through several milestones in web development history.

Why the Emergence of Standalone Components?

Increased Complexity in Web Applications

As web applications evolved from simple, static pages to complex, dynamic apps (often referred to as Single Page Applications or SPAs), developers faced challenges with code organization and scalability. Traditional HTML, CSS, and JavaScript codebases became harder to manage due to:

  • Global namespace collisions in JavaScript
  • Tight coupling of UI elements and behavior
  • Difficulty in reusability across different parts of an application

Standalone components started providing a way to encapsulate behavior, styling, and structure into isolated, self-contained units, making it easier to manage and scale large applications.

Modularity and Reusability

Standalone components promote reusability by allowing developers to create self-sufficient, modular building blocks. Components can be easily reused across different parts of an application or even across multiple applications. By adopting a component-driven architecture:

  • Components become portable and independent of the rest of the application.
  • Code can be easily reused and shared without dependency issues.
  • Teams can collaborate more efficiently, with different groups working on distinct components.

Improved Developer Experience (DX)

Standalone components improve the overall development experience by:

  • Reducing the need for boilerplate code.
  • Providing clear boundaries for state and behavior.
  • Making testing and debugging more straightforward since each component is self-contained.
  • Allowing teams to quickly prototype new features or layouts without overhauling large parts of the codebase.

Separation of Concerns

Standalone components encourage a clean separation between the different parts of a web application, such as:

  • Presentation logic (HTML templates and CSS styles)
  • Business logic (JavaScript functions and data management)

This separation ensures that each part of an application is clearly defined and can be worked on independently, reducing the chance of unintended side effects.

React, Angular, and Vue Pushing the Component Paradigm

Modern JavaScript frameworks like React, Angular, and Vue champion the idea of components. They helped popularize standalone components by providing:

  • A clear API for building and managing components.
  • Encouragement for breaking applications into small, reusable pieces.
  • Support for lifecycle methods, state management, and data binding, which further enhances modularity and isolation.

As these frameworks are growing in popularity, the component-based architecture is becaming a standard for building web applications. Standalone components in these frameworks are key to handling the complexity of state management, routing, and DOM manipulation in a structured way.

Historical Timeline and Key Milestones

  1. (Early 2000s) Rise of JavaScript and AJAX: Before components became a mainstream idea, web development primarily relied on traditional HTML, CSS, and JavaScript files that were tightly coupled. JavaScript libraries like jQuery became popular for handling DOM manipulation and event handling, but the lack of structure often led to what developers call “spaghetti code.”
  2. (2006) Introduction of MVC with AngularJS: AngularJS, released by Google in 2006, was one of the first frameworks to introduce a Model-View-Controller (MVC) pattern to web development. While AngularJS didn’t yet have the fully realized concept of standalone components, it paved the way for modular architecture by encouraging developers to think about their application in terms of reusable pieces (directives and controllers).
  3. (2013) React and the Component Revolution: Facebook released React in 2013, which popularized the idea of component-based architecture. React introduced the concept of declarative UI and reusable components that could encapsulate their own state and behavior. Components in React were self-contained units that could be easily composed to build complex user interfaces. React’s approach to web development emphasized unidirectional data flow and component isolation, encouraging developers to break their UI into small, reusable components. This helped tackle the problem of scalability and maintainability in large-scale web apps.
  4. (2014) Vue.js and Simplicity in Component-Based Architecture: Vue.js, released in 2014, followed a similar pattern to React and Angular by offering a simple API for creating standalone, reusable components. Vue promoted an approachable learning curve, making it easy for developers to break their application down into manageable parts.
  5. (2016) Angular 2 and Beyond: Angular (the complete rewrite of AngularJS, starting from version 2) introduced a fully component-based architecture. Angular components became the building blocks of an application, and the framework encouraged modularization and the use of services to handle business logic. Angular’s standalone components were introduced later (in Angular v14), allowing developers to create components without relying on Angular modules, further streamlining the development process.
  6. Modern Era (2020s): Modern frameworks and libraries have continued to evolve with better support for standalone components. For example, Angular 14’s standalone components further decouple components from module dependencies, simplifying app design and improving flexibility. This is part of a broader movement toward modular web development across all modern frameworks, aligning with trends like micro frontends and modular monoliths.

Example: Weather Chart

I will take Angular 17 into account while writing this example.

1. Setup

Ensure you have Angular CLI installed and create a new Angular project if you haven’t already.

ng new weather-app
cd weather-app

Install Highcharts and the highcharts-angular package.

npm install highcharts highcharts-angular

2. Create a Standalone Component

Create a standalone component named WeatherChartComponent:

ng generate component weather-chart --standalone

3. Implement the Component

Edit the weather-chart.component.ts file to fetch weather data and display it using Highcharts:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import Highcharts from 'highcharts';
import { Chart } from 'highcharts';

@Component({
selector: 'app-weather-chart',
standalone: true,
templateUrl: './weather-chart.component.html',
styleUrls: ['./weather-chart.component.css']
})
export class WeatherChartComponent implements OnInit {
chart: Chart | undefined;

constructor(private http: HttpClient) {}

ngOnInit(): void {
this.fetchWeatherData();
}

fetchWeatherData(): void {
const apiKey = 'YOUR_API_KEY'; // Replace with your actual API key
const city = 'London'; // Replace with the desired city
const url = `https://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=${apiKey}`;

this.http.get(url).subscribe((data: any) => {
this.renderChart(data);
});
}

renderChart(data: any): void {
const temperatures = data.list.map((entry: any) => ({
x: new Date(entry.dt * 1000).getTime(),
y: entry.main.temp - 273.15 // Convert from Kelvin to Celsius
}));

this.chart = Highcharts.chart('container', {
title: {
text: 'Weather Forecast'
},
xAxis: {
type: 'datetime',
title: {
text: 'Date'
}
},
yAxis: {
title: {
text: 'Temperature (°C)'
}
},
series: [{
name: 'Temperature',
data: temperatures
}]
});
}
}

4. Create the HTML Template

Edit the weather-chart.component.html file to include a container for the Highcharts chart:

<div id="container" style="width: 100%; height: 400px;"></div>

5. Add Styling (Optional)

Edit weather-chart.component.css file to add any desired styling:

/* weather-chart.component.css */
#container {
margin: 0 auto;
padding: 20px;
}

6. Register the Component

Make sure to include the HttpClientModule in your app.module.ts or in the module where you use the WeatherChartComponent:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { WeatherChartComponent } from './weather-chart/weather-chart.component';

@NgModule({
declarations: [],
imports: [
BrowserModule,
HttpClientModule,
WeatherChartComponent // Import the standalone component
],
providers: [],
bootstrap: [WeatherChartComponent]
})
export class AppModule { }

7. Use the Component

Finally, you can use the WeatherChartComponent in your application by using the selector of the component. For example, in your app.component.html

<app-weather-chart></app-weather-chart>

This standalone Angular component fetches weather data from an API and displays it in a Highcharts chart. Make sure to replace the placeholder API key and city with real values. You can further customize the chart and the component as needed.

--

--

Vikesh Mittal
Vikesh Mittal

Written by Vikesh Mittal

User Interface Architect | Passionate about Micro-frontends | Angular | React | https://vikeshmittal.com/

No responses yet