You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular项目构建完成后动态注入Google Font字体

可以通过运行时动态插入link标签 + 外置配置文件的方案实现需求,无需为不同部署单独构建版本,具体实现步骤如下:

1. 新增外置可修改的配置文件

在项目assets目录下新建config.json配置文件,该文件在打包后属于独立静态资源,部署时直接修改即可生效:

{
  "googleFont": {
    "family": "Roboto",
    "weights": [300, 400, 500],
    "display": "swap"
  }
}

2. 实现配置加载与字体注入逻辑

新增全局配置服务ConfigService,在应用启动阶段读取配置并动态插入字体link标签:

// config.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({ providedIn: 'root' })
export class ConfigService {
  fontConfig: Record<string, any>;

  constructor(private http: HttpClient) {}

  loadAppConfig(): Promise<void> {
    return this.http.get<Record<string, any>>('/assets/config.json')
      .toPromise()
      .then(res => {
        this.fontConfig = res.googleFont;
        this.injectGoogleFont();
      });
  }

  private injectGoogleFont(): void {
    const { family, weights, display } = this.fontConfig;
    // 动态创建link标签
    const fontLink = document.createElement('link');
    fontLink.rel = 'stylesheet';
    fontLink.href = `https://fonts.googleapis.com/css?family=${family}:${weights.join(',')}&display=${display}`;
    document.head.appendChild(fontLink);
    // 同步更新全局CSS字体变量
    document.documentElement.style.setProperty('--main-font', `'${family}', sans-serif`);
  }
}

3. 注册启动钩子执行初始化逻辑

在app.module.ts中注册Angular启动前置钩子APP_INITIALIZER,保证配置加载和字体注入在应用渲染前完成:

// app.module.ts
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { ConfigService } from './config.service';
import { AppComponent } from './app.component';

function initApp(config: ConfigService) {
  return () => config.loadAppConfig();
}

@NgModule({
  imports: [BrowserModule, HttpClientModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent],
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: initApp,
      deps: [ConfigService],
      multi: true
    }
  ]
})
export class AppModule {}

4. 全局样式适配

在全局样式文件styles.css中使用CSS变量定义默认字体,动态加载的字体生效后会自动适配:

:root {
  --main-font: sans-serif;
}
* {
  font-family: var(--main-font);
}

注意事项

  • 原index.html中静态写入的Google Font link标签可以直接删除,避免冲突
  • 如果需要支持多个自定义字体,只需扩展config.json结构,在注入逻辑中循环创建link标签即可
  • 配置中的display: swap属性会优先显示系统默认字体,字体加载完成后自动替换,可避免页面内容闪烁问题

内容的提问来源于stack exchange,提问作者phunder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 01:00:04