# Angular 头像库:在 Angular 中使用 DiceBear
DiceBear 可以通过 Signals(Angular 17+)或 `OnChanges` 生命周期钩子集成到 Angular 组件中。使用 JavaScript 库可在客户端生成 SVG 头像,或者使用 HTTP API 作为一个简单的 `
` 来源,无需额外依赖。
你可以通过 [JS-Library](https://dicebear.zhcndoc.com/how-to-use/js-library/) 或 [HTTP-API](https://dicebear.zhcndoc.com/how-to-use/http-api/) 在 Angular 中使用 DiceBear。
## 使用 JS 库
```typescript [Angular 17+]
import { Component, input, computed } from '@angular/core';
import { Style, Avatar } from '@dicebear/core';
import lorelei from '@dicebear/styles/lorelei.json' with { type: 'json' };
const style = new Style(lorelei);
@Component({
selector: 'app-avatar',
template: `
`,
})
export class AvatarComponent {
seed = input('Alice');
avatarUrl = computed(() =>
new Avatar(style, {
seed: this.seed(),
size: 128,
// ... 其他选项
}).toDataUri(),
);
}
```
```typescript [Angular 16 and earlier]
import { Component, Input, OnChanges } from '@angular/core';
import { Style, Avatar } from '@dicebear/core';
import lorelei from '@dicebear/styles/lorelei.json' with { type: 'json' };
const style = new Style(lorelei);
@Component({
selector: 'app-avatar',
standalone: true,
template: `
`,
})
export class AvatarComponent implements OnChanges {
@Input() seed: string = 'Alice';
avatarUrl: string = '';
ngOnChanges() {
this.avatarUrl = new Avatar(style, {
seed: this.seed,
size: 128,
// ... 其他选项
}).toDataUri();
}
}
```
## Use HTTP API
```typescript [Angular 17+]
import { Component, input, computed } from '@angular/core';
@Component({
selector: 'app-avatar',
template: `
`,
})
export class AvatarComponent {
seed = input('Alice');
avatarUrl = computed(() => {
const url = new URL('https://api.dicebear.com/10.x/lorelei/svg');
url.searchParams.set('seed', this.seed());
url.searchParams.set('size', '128');
// ... other options
return url.href;
});
}
```
```typescript [Angular 16 and earlier]
import { Component, Input, OnChanges } from '@angular/core';
@Component({
selector: 'app-avatar',
standalone: true,
template: `
`,
})
export class AvatarComponent implements OnChanges {
@Input() seed: string = 'Alice';
avatarUrl: string = '';
ngOnChanges() {
const url = new URL('https://api.dicebear.com/10.x/lorelei/svg');
url.searchParams.set('seed', this.seed);
url.searchParams.set('size', '128');
// ... other options
this.avatarUrl = url.href;
}
}
```