【问题标题】:How to change location of favIcon in angular 11 based on some condition如何根据某些条件更改 Angular 11 中 favIcon 的位置
【发布时间】:2021-10-17 00:23:13
【问题描述】:

我正在使用 Angular 11,我可以在其中加载/显示位于 src 文件夹中的 favicon。但是我的要求是如果我将 favicon 的位置放在 config 变量中,那么我的要求是使其可配置,以便它可以根据我提供的值获取 favicon 的位置配置文件。注意:我们只在部署之前更改配置变量。

我尝试过使用很多东西,但没有什么对我有用。只有我能够获得位于源文件夹中的 favicon。 在app.component.html

<head>
  <meta charset="utf-8">
  <title>Test</title>
  <base href="./">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" id ="favIcon"  href="assets/{{favIcon}}">
</head>
<body>
</body>

app.component.ts 文件中,favIcon 变量设置为images/favicon1.ico

我们已尝试使用 app.component.ts 中的文档选择器通过 JavaScript 更改此设置

this.favicon = document.getElementById('favIcon');
this.favicon.href = this._sanitizer.bypassSecurityTrustUrl("assets/images/rdh-favIcon.ico");

您能否提供任何解决方案,以便我可以使用来自不同位置的不同 favicon

在 angular.json 中

 "assets": ["src/favicon.ico",
             "src/assets"],

【问题讨论】:

    标签: javascript html angular favicon angular11


    【解决方案1】:

    在你的app.component.html

    <link rel="icon" id ="favIcon" type="image/x-icon" href="favicon.ico">
    

    在你的app.component.ts

    export class AppComponent {
      favIcon: HTMLLinkElement = document.querySelector('#favIcon');
    
      changeIcon() {
        this.favIcon.href = 'https://www.google.com/favicon.ico';
      }
    }
    

    对于Angular 12.x 替换

    favIcon: HTMLLinkElement = document.querySelector('#favIcon')

    favIcon: any = document.querySelector('#favIcon')

    别忘了在你的app.component.html 的某个地方添加一个button 来执行这个changeIcon() 函数。

    <button (click)="changeIcon()">Change favicon</button>
    

    希望这会有所帮助。

    【讨论】:

    • 我们希望在加载页面之前而不是在单击按钮时更改网站图标
    猜你喜欢
    • 2022-07-29
    • 2011-02-09
    • 1970-01-01
    • 2019-11-07
    • 2023-03-18
    • 2019-10-24
    • 2016-02-10
    • 1970-01-01
    • 2014-07-25
    相关资源
    最近更新 更多