Install ngx-avatar
Install the ngx-avatar
library via npm:
npm i ngx-avatar
Import NgxAvatarModule
Add the NgxAvatarModule
to your application. Open app.module.ts
and update it as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; // Optional for form handling import { AppComponent } from './app.component'; import { NgxAvatarModule } from 'ngx-avatar'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, FormsModule, NgxAvatarModule // Import ngx-avatar module ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } |
4. Add a Basic Avatar Example
Now let’s add a simple example of creating avatars in app.component.ts
and app.component.html
.
app.component.ts
Here we define sample user data for testing:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { // User data user1 = { name: 'John Doe', email: 'john.doe@example.com', imageUrl: 'https://randomuser.me/api/portraits/men/32.jpg' }; user2 = { name: 'Jane Smith', email: 'jane.smith@example.com', imageUrl: '' }; } |
app.component.html
Display avatars based on user data:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<div class="avatar-demo"> <h1>User Profile Avatars</h1> <!-- Avatar with Image URL --> <div> <h3>{{ user1.name }}</h3> <ngx-avatar [src]="user1.imageUrl" [size]="100"></ngx-avatar> </div> <!-- Avatar with Initials --> <div> <h3>{{ user2.name }}</h3> <ngx-avatar [name]="user2.name" [size]="100" [bgColor]="'#ff5722'" [textColor]="'#ffffff'"></ngx-avatar> </div> <!-- Avatar with Gravatar --> <div> <h3>Gravatar (Email-Based)</h3> <ngx-avatar [email]="user2.email" [size]="100"></ngx-avatar> </div> </div> |
FULL SOURCE CODE