Angular 9-从数据库导入字体名称和字体url



在数据库中,我有字体名称和字体url,这些数据可以由用户从UI中更改。

在我的angular应用程序中,我应该从API获取数据并将其存储在css中,这样我的应用程序就可以使用选定的字体运行。

我试图将自定义变量解析为styles.css,例如按钮颜色,但在这种情况下,它不起作用。

你能帮我吗?

完整示例

这是我的NodeJs服务器:

这里我有2个谷歌字体

const fonts = [
{
id: 1,
name: `Quicksand`,
url: 'https://fonts.googleapis.com/css?family=Quicksand'
},
{
id: 2,
name: `Anton`,
url: 'https://fonts.googleapis.com/css?family=Anton'
}
]
app.get('/', (req, res, next) => {
res.send(fonts)
})
const PORT = process.env.PORT || 3000
app.listen(PORT, () => {
console.log(`Server is running on PORT : ${PORT}`)
})

在Angular客户端中:

我创建了一个字体类:

export class Font {
public id: number;
public name: string;
public url: string;
}

app.component.ts

fonts$: Observable<Font>;
constructor(private http: HttpClient) { }
ngOnInit(): void {
this.fonts$ = this.http.get<Font>('http://localhost:3000')
}
applyFontToBody(font: Font) {
const id = `font-${font.name}-${font.id}`;
if (!document.getElementById(id)) {
let style = document.createElement('link');
style.setAttribute('href', font.url);
style.setAttribute('rel', 'stylesheet')
style.setAttribute('id', id)
document.head.appendChild(style);
}

document.getElementsByTagName('body')[0].style.fontFamily = font.name;
}

app.component.html

<div class="border p-4">
<h5>
In App Component
</h5>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Illum consectetur enim, natus sed dicta modi nemo
</p>
</div>
<ng-container *ngIf="(this.fonts$ | async) as fonts">
<table class="table table-striped">
<thead>
<tr>
<td>#</td>
<td>Name</td>
<td>Url</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of this.fonts; let idx=index">
<td>{{idx+1}}</td>
<td>{{item.name}}</td>
<td>{{item.url}}</td>
<td>
<button class="btn btn-sm btn-primary" (click)="applyFontToBody(item)" type="button">
Apply To Body
</button>
</td>
</tr>
</tbody>
</table>
</ng-container>

最新更新