835
0
0
How to Build an Angular 18 Google Font Picker with PrimeNG Without an API Key

How to Build an Angular 18 Google Font Picker with PrimeNG Without an API Key

Published on January 7, 2025 by M. Maxim

How to Create an Angular 18 Google Font Picker Using PrimeNG

Discover how to build a user-friendly font picker in Angular using PrimeNG and Google Fonts. This guide provides a complete walkthrough, from setting up the project to creating an intuitive font selection interface.

Step 1: Set Up the Angular Project

The first step is to create a new Angular project. If you’re new to Angular, this involves running a command to scaffold your application. Here’s how:

ng new angular-font-picker

Once your project is ready, you need to install PrimeNG and PrimeIcons. These libraries provide the essential UI components for our project. Since we are using Angular 18, we’ll install PrimeNG version 18:

npm install primeng@18 @primeng/themes primeicons

If you’re unfamiliar with PrimeNG, it’s a popular UI library for Angular applications that offers a wide range of pre-designed components. You can find more installation details on the official PrimeNG setup page.

Step 2: Add Google Fonts

Google Fonts offers a vast collection of free and stylish fonts for web projects. To integrate them into our application, create a new file called global-data.ts in the src/app directory. This file will store a list of font names as an array.

Why store fonts in a separate file? It keeps your code organized and allows you to easily modify the font list in one place without affecting other components. Here’s an example:

export const GoogleFonts = [
  "ABeeZee", "Abel", "Abril Fatface", "Aclonica", "Acme",
  "Actor", "Adamina", "Advent Pro", "Aguafina Script", ...
];

Step 3: Build the Angular Component

Now that we have the fonts list, it’s time to create the component that will display and manage the font picker. The AppComponent will handle tasks like filtering fonts, dynamically loading Google Fonts, and binding the selected font to the UI.

The Angular component combines TypeScript for logic, PrimeNG for the dropdown UI, and Google Fonts API for font loading. Below is the complete code for the AppComponent:

import { Component, OnInit } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { GoogleFonts } from "./global-data";
import { CommonModule } from "@angular/common";
import { FormsModule } from "@angular/forms";
import { FloatLabelModule } from "primeng/floatlabel";
import { SelectModule } from "primeng/select";

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [
    RouterOutlet,
    CommonModule,
    FormsModule,
    FloatLabelModule,
    SelectModule
  ],
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss'
})
export class AppComponent implements OnInit {
  filteredFonts: any = [];
  loadedFonts: string[] = [];
  baseFont: any;

  ngOnInit(): void {
    this.baseFont = { name: 'ABeeZee' };
    this.filterFonts({ filter: "" });
  }

  filterFonts(event: any): void {
    const query = event.filter.toLowerCase();
    this.filteredFonts = GoogleFonts
      .filter(fn => fn.toLowerCase().includes(query))
      .slice(0, 10)
      .map(fn => ({ name: fn }));
    this.filteredFonts.forEach((font: any) => this.loadFont(font.name));
  }

  loadFont(fontName: string): void {
    const fontFamily = fontName.replace(/ /g, '+');
    const encodedFont = btoa(fontName.toLowerCase());

    if (!this.loadedFonts.includes(encodedFont)) {
      const fontLink = document.createElement('link');
      fontLink.rel = 'stylesheet';
      fontLink.href = `https://fonts.googleapis.com/css?family=${fontFamily}:100,200,300,400,500,600,700,800,900`;
      document.head.appendChild(fontLink);

      this.loadedFonts.push(encodedFont);
    }
  }
}

Step 4: Create the HTML Template

The next step is designing the interface for the font picker. We’ll use PrimeNG’s p-select component for the dropdown. This component allows users to filter fonts, view them in their respective styles, and select a font of their choice.

<div class="flex align-items-center justify-content-center center-div">
  <p-floatlabel variant="on">
    <p-select
      [options]="filteredFonts"
      [(ngModel)]="baseFont"
      optionLabel="name"
      [filter]="true"
      filterBy="name"
      [showClear]="false"
      class="w-full"
      (onFilter)="filterFonts($event)">
      <ng-template let-font #item>
        <div [style.font-family]="font.name">{{ font.name || baseFont.name }}</div>
      </ng-template>
      <ng-template #selectedItem let-selectedOption>
        <div [style.font-family]="selectedOption.name">
          {{ selectedOption.name || baseFont.name }}
        </div>
      </ng-template>
    </p-select>
    <label>Select Font</label>
  </p-floatlabel>
</div>

The design ensures that the dropdown preview matches the actual font styles, providing a seamless user experience.

Additional Resources

With this implementation, you now have a fully functional Angular font picker that dynamically loads Google Fonts. This feature can be integrated into various applications, such as text editors or design tools, to enhance the user experience.

If you want to explore the source code or contribute to the project, visit the GitHub repository. Don’t hesitate to share your thoughts or suggest improvements!

Comments (0)

No comments yet. Be the first to comment!

Leave a Comment
Replying to someone's comment. Cancel
835
0
0
Join Our OBS Community

Loading...

Join Now