Avatar component with a fallback
Angular · Angular · intermediate · greenfield
Adds the avatar component: computes the image URL from the src input, falling back to a name-based placeholder when src is missing. Standalone, renders the resolved URL.
Requirements
- Show the user's avatar from the `src` input.
- When `src` is empty, show a generated fallback based on the `name` input.
- Standalone component; the fallback must reflect the actual inputs at render time.
Files touched
- src/app/components/avatar.ts
--- src/app/components/avatar.ts
+import { Component, Input } from '@angular/core';
+
+@Component({
+ selector: 'app-avatar',
+ template: `<img [src]="url" alt="" />`,
+})
+export class Avatar {
+ @Input() src = '';
+ @Input() name = '';
+
+ url: string;
+
+ constructor() {
+ this.url = this.src || `https://ui-avatars.com/api/?name=${encodeURIComponent(this.name)}`;
+ }
+}