首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >动态定义页面方向-角5

动态定义页面方向-角5
EN

Stack Overflow用户
提问于 2018-05-07 13:00:03
回答 3查看 5.1K关注 0票数 6

我试图在我的角5项目上动态地设置页面方向(RTL或LTR)。

index.html中,如果我用body标记或app-root选择器静态地编写一个或另一个,工作正常。

代码语言:javascript
复制
<body dir="rtl">
  <app-root></app-root>
</body>

但是,如果我尝试动态设置(例如使用一个名为textDir的变量),什么都不会发生(它保留标准值LTR值):

index.html

代码语言:javascript
复制
<body [dir]="textDir">
  <app-root></app-root> <!-- I tried also <app-root [dir]="textDir"></app-root> with no success -->
</body>

app.component.ts

代码语言:javascript
复制
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没有影响。我怎么能这么做?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-05-07 13:08:27

index.html中没有进行模板绑定。为此,您必须在app.component.html中创建一个根元素,如下所示:

app.component.html

代码语言:javascript
复制
<div [dir]="textDir">
  <!-- rest of app template -->
</div>
票数 5
EN

Stack Overflow用户

发布于 2019-04-10 08:15:39

您可以在应用组件承包商中使用document.dir,它将dir设置为html标记,并可以使用变量传递它。

代码语言:javascript
复制
direction : string = "rtl";
constructor() {
  document.dir = this.direction;
} 
票数 5
EN

Stack Overflow用户

发布于 2021-03-10 08:38:24

穆斯塔法·赛义德链接之后,我在mgx()的翻译函数中编写了以下代码。

代码语言:javascript
复制
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

代码语言:javascript
复制
<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..

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50214861

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档