DEV Community

Cover image for Generating Dynamic Avatars in Angular Using DiceBear.
David Ongora
David Ongora

Posted on

Generating Dynamic Avatars in Angular Using DiceBear.

User interface personalization has become a cornerstone of modern web applications.
Ever thought of replacing boring user initials with unique, dynamic avatars? With DiceBear https://www.dicebear.com/, you can generate custom, SVG-based avatars right in your Angular app—perfect for user profiles, comments,leaderboards or dashboards.

sample of profile with initials
use of person initials

it looks nice if we give an avatar closer to is name or attributes that define him

here is one for a coding guru or rather a geek
use of avatar images

Step 1: Install DiceBear
Choose your package manager:

npm

npm install @dicebear/core @dicebear/collection --save
Enter fullscreen mode Exit fullscreen mode

pnpm

pnpm install @dicebear/core @dicebear/collection --save

Enter fullscreen mode Exit fullscreen mode

Step 2: Generate Avatars in Angular

import { createAvatar } from '@dicebear/core';
import { openPeeps } from '@dicebear/collection';
Enter fullscreen mode Exit fullscreen mode

then in your component

generateAvatar(StudentName: string): SafeUrl | null {
    try {
      if (typeof createAvatar === 'function' && openPeeps) {
        console.log('name passed to dicebear:', StudentName);
        const avatar = createAvatar(openPeeps, {
          seed: StudentName,
          backgroundColor: ['#E7EDF4'],
          scale: 80
        }).toString();
        return this.sanitizer.bypassSecurityTrustUrl(`data:image/svg+xml;utf8,${encodeURIComponent(avatar)}`);
      }
    } catch (error) {
      console.error('Failed to generate avatar:', error);
      // Fallback to empty or default avatar
      // this.myAvatar = this.sanitizer.bypassSecurityTrustUrl('path/to/default-avatar.svg');
    }
    return null; // Return null if avatar generation fails 
  }
}
Enter fullscreen mode Exit fullscreen mode

Template Usage

<div class="h-9 w-9 flex-shrink-0 rounded-full overflow-hidden bg-gray-200">
<img [src]="generateAvatar(entry.student.fullname)" alt="Avatar" class="w-full h-full object-cover">
</div>
Enter fullscreen mode Exit fullscreen mode

why sanitize the urls
to avoid getting this warning

Without Sanitization
Without Sanitization

Without Sanitization you get errors

Step 3: Why Sanitize the URL?
Angular blocks unsafe dynamic URLs by default to prevent XSS attacks. Since DiceBear generates SVG markup, we must sanitize it using DomSanitizer

how to sanitize the url
you can import the safeurl or use it as a pipe if you have it(custom one its not a core pipe).

import { DomSanitizer, SafeUrl } from '@angular/platform-browser';

Enter fullscreen mode Exit fullscreen mode
return this.sanitizer.bypassSecurityTrustUrl(`data:image/svg+xml;utf8,${encodeURIComponent(avatar)}`);
Enter fullscreen mode Exit fullscreen mode

Before
leaderboard using initials

Results
The transformation from static initials to dynamic avatars significantly enhances user interface engagement:
leaderboard using avatars

Names passed as seed to generate those avatars
names passed as 'seed'

Why Use DiceBear?

  1. No external API calls (avatars are generated on the frontend)
  2. Highly customizable (choose from multiple styles like lorelei, bottts, open-peeps, etc.)
  3. Deterministic (same input = same avatar every time)
  4. Lightweight (SVG-based, no heavy images)

Full Implementation
avatar.component.ts


import { createAvatar } from '@dicebear/core';
import { openPeeps } from '@dicebear/collection';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';

@Component({
  selector: 'app-avatar',
  templateUrl: './avatar.component.html',
})
export class AvatarComponent {

  constructor(private sanitizer: DomSanitizer) {}

  generateAvatar(StudentName: string): SafeUrl | null {
    try {
      if (typeof createAvatar === 'function' && openPeeps) {
        console.log('name passed to dicebear:', StudentName);
        const avatar = createAvatar(openPeeps, {
          seed: StudentName,
          backgroundColor: ['#E7EDF4'],
          scale: 80
        }).toString();
        return this.sanitizer.bypassSecurityTrustUrl(`data:image/svg+xml;utf8,${encodeURIComponent(avatar)}`);
      }
    } catch (error) {
      console.error('Failed to generate avatar:', error);
      // Fallback to empty or default avatar
      // this.myAvatar = this.sanitizer.bypassSecurityTrustUrl('path/to/default-avatar.svg');
    }
    return null; // Return null if avatar generation fails 
  }
  }
}
Enter fullscreen mode Exit fullscreen mode

avatar.component.html

<div class="h-9 w-9 flex-shrink-0 rounded-full overflow-hidden bg-gray-200">
<img [src]="generateAvatar(entry.student.fullname)" alt="Avatar" class="w-full h-full object-cover">
</div>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)