动态定义页面方向 - Angular 5

问题描述 投票:0回答:2

我正试图在我的Angular 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没有影响。我怎样才能做到这一点?

javascript angular direction
2个回答
2
投票

index.html中没有完成模板绑定。为此,你必须在你的app.component.html中创建一个根元素,如:

app.component.html

<div [dir]="textDir">
  <!-- rest of app template -->
</div>

0
投票

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

direction : string = "rtl";
constructor() {
  document.dir = this.direction;
} 
© www.soinside.com 2019 - 2024. All rights reserved.