【问题标题】:Angular - Update html attribute in root index.htmlAngular - 更新根 index.html 中的 html 属性
【发布时间】:2020-01-14 02:25:37
【问题描述】:

我的 index.html 中有以下内容

<!doctype html>
<html dir="ltr" lang="en">
    <head>
        <meta charset="utf-8">
        <title>Halls Gate</title>
        <base href="/">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="icon" type="image/png" href="assets/img/favicon.png">
        <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,500,600,700" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Istok+Web" rel="stylesheet">
    </head>
    <body>
        <app-root></app-root>
    </body>
</html>

我想根据所选语言从组件 &lt;html dir="ltr" lang="en"&gt; 更新 html 元素中的 dir 和 lang 属性。

有没有办法在 Angular 中解决这个问题?

谢谢。

【问题讨论】:

    标签: angular angular7


    【解决方案1】:

    我认为,它可以简单地改变......

    https://stackblitz.com/edit/angular-ih2drk?file=src%2Fapp%2Fapp.component.ts

    import { Component, Renderer2 } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      name = 'Angular 6';
      constructor(private renderer: Renderer2) {
        this.renderer.setAttribute(document.querySelector('html'), 'lang', 'tr');
      }
    }
    
    

    【讨论】:

    • 谢谢,感谢您的帮助。这是完美的工作。
    【解决方案2】:

    这将是一个不好的做法。您应该改用Internationalization。 国际化是设计和准备您的应用程序以可用于不同语言的过程。本地化是将您的国际化应用翻译成特定语言环境的特定语言的过程。

    从以下开始:

    ng serve --configuration=your locale id
    

    【讨论】:

    • 我正在使用github.com/ngx-translate/coregithub.com/Greentube/localize-router 并且效果很好,我没有使用角度国际化,我会看看它。
    • 库存永远是最好的 ;)
    • 大声笑,比方说,没有必要重新发明轮子,无论如何,感谢您的帮助。谢谢你。我肯定会按照您的建议进行操作,只是想掌握它并真正了解其中的区别。
    • 仅当您的&lt;app-root&gt;&lt;/app-root&gt; 在 index.html 的正文中时,这样做不会更改 html 标记的 lang 属性。我觉得这个答案与问题关系不大。
    【解决方案3】:

    如果您使用 angular-i18n 并希望根据构建更改语言环境,您可以这样做

    import {Component, Inject, LOCALE_ID} from '@angular/core';
    import {DOCUMENT} from '@angular/common'; 
    ...
    export class AppComponent implements OnInit {
      ...
      constructor(@Inject(DOCUMENT) private document: Document, @Inject(LOCALE_ID) locale: string) {
         this.document.documentElement.lang  = locale;
      }
      ...
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-19
      • 2018-06-22
      • 1970-01-01
      • 1970-01-01
      • 2022-07-29
      • 2020-08-08
      • 2023-02-06
      • 2011-09-17
      • 1970-01-01
      相关资源
      最近更新 更多