Angular - Update html attribute in root index.html

馋奶兔 提交于 2020-01-24 01:28:19

问题


I have following content in my 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>

I want to update dir and lang attribute in html element from a component <html dir="ltr" lang="en"> based on the language selected.

Is there a way to go about this in Angular?

Thank you.


回答1:


I think, it can be changed simply...

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:


This will be a bad practice. You should use Internationalization instead. Internationalization is the process of designing and preparing your app to be usable in different languages. Localization is the process of translating your internationalized app into specific languages for particular locales.

Make your start with:

ng serve --configuration=your locale id



回答3:


If you are using angular-i18n and want to change locale based on build, you can do this

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;
  }
  ...
}


来源:https://stackoverflow.com/questions/54203912/angular-update-html-attribute-in-root-index-html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!