我试图在我的角5项目上动态地设置页面方向(RTL或LTR)。
在index.html中,如果我用body标记或app-root选择器静态地编写一个或另一个,工作正常。
<body dir="rtl">
<app-root></app-root>
</body>但是,如果我尝试动态设置(例如使用一个名为textDir的变量),什么都不会发生(它保留标准值LTR值):
index.html
<body [dir]="textDir">
<app-root></app-root> <!-- I tried also <app-root [dir]="textDir"></app-root> with no success -->
</body>app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
public textDir;
lang = sessionStorage.getItem("lang");
constructor() {
if(this.lang === "he"){
this.textDir = 'rtl';
}
else {
this.textDir = 'ltr';
}
console.log(this.textDir);
}
}console.log根据条件显示正确的方向,但对index.html没有影响。我怎么能这么做?
发布于 2018-05-07 13:08:27
在index.html中没有进行模板绑定。为此,您必须在app.component.html中创建一个根元素,如下所示:
app.component.html
<div [dir]="textDir">
<!-- rest of app template -->
</div>发布于 2019-04-10 08:15:39
您可以在应用组件承包商中使用document.dir,它将dir设置为html标记,并可以使用变量传递它。
direction : string = "rtl";
constructor() {
document.dir = this.direction;
} 发布于 2021-03-10 08:38:24
在穆斯塔法·赛义德链接之后,我在mgx()的翻译函数中编写了以下代码。
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);
}
}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>由于我使用的是not,它内置了对rtl-ltr方向的支持,所以我不必再使用css..
https://stackoverflow.com/questions/50214861
复制相似问题