Javascript 动态定义页面方向-角度5
我正在尝试在Angular 5项目中动态设置页面方向(RTL或LTR) 在index.html中,如果我在body标记或应用程序根选择器中静态地编写一个或另一个,则工作正常Javascript 动态定义页面方向-角度5,javascript,angular,direction,Javascript,Angular,Direction,我正在尝试在Angular 5项目中动态设置页面方向(RTL或LTR) 在index.html中,如果我在body标记或应用程序根选择器中静态地编写一个或另一个,则工作正常 <body dir="rtl"> <app-root></app-root> </body> console.log根据条件显示正确的方向,但对index.html没有影响。 我该怎么做?在index.html中没有模板绑定。为此,您必须在app.component.ht
<body dir="rtl">
<app-root></app-root>
</body>
console.log
根据条件显示正确的方向,但对index.html
没有影响。
我该怎么做?在
index.html
中没有模板绑定。为此,您必须在app.component.html
中创建一个根元素,如:
app.component.html
<div [dir]="textDir">
<!-- rest of app template -->
</div>
您可以在应用程序组件承包商中使用document.dir,它会将dir设置为您的html标记,并可以通过变量传递
direction : string = "rtl";
constructor() {
document.dir = this.direction;
}
接下来,我在mgx translate switchLang()的translate函数中编写了以下代码
translater.component.html
<select #selectedLang (change)="switchLang(selectedLang.value)">
<option *ngFor="let language of translate.getLangs()" [value]="language"
[selected]="language === translate.currentLang">
{{ language | uppercase }}
</option>
</select>
{{语言|大写}}
当我使用内置支持的ngx基金会时,我不必再使用任何css。AppComponent中的值只能从
app.component.html
获得,而不能从index.html
direction : string = "rtl";
constructor() {
document.dir = this.direction;
}
import { DOCUMENT } from '@angular/common';
import { Component, Inject, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-translater',
templateUrl: './translater.component.html',
styleUrls: ['./translater.component.scss']
})
export class TranslaterComponent implements OnInit {
constructor(public translate: TranslateService, @Inject(DOCUMENT) private document: Document) { }
ngOnInit(): void {
this.translate.addLangs(['en', 'ar']);
this.translate.setDefaultLang('en');
}
switchLang(lang: string) {
const htmlTag = this.document.getElementsByTagName("html")[0] as HTMLHtmlElement;
htmlTag.dir = lang === "ar" ? "rtl" : "ltr";
htmlTag.lang = lang;
this.translate.use(lang);
}
}
<select #selectedLang (change)="switchLang(selectedLang.value)">
<option *ngFor="let language of translate.getLangs()" [value]="language"
[selected]="language === translate.currentLang">
{{ language | uppercase }}
</option>
</select>