Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining page direction dynamically - Angular 5

I'm trying to set the page direction (RTL or LTR) dynamically on my Angular 5 project.

In index.html, if I write statically one or another in body tag or app-root selector, works fine.

<body dir="rtl">
  <app-root></app-root>
</body>

However, if I try to set dynamically, e.g using a variable called textDir, nothing happens (it keeps the standard value, LTR value):

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

}

The console.log displays the correct direction, according to the conditional, but has no effect on index.html. How can I do that?

like image 581
Atoyansk Avatar asked Dec 24 '22 07:12

Atoyansk


2 Answers

There is no template binding done in the index.html. For this you have to make a root element inside your app.component.html like:

app.component.html

<div [dir]="textDir">
  <!-- rest of app template -->
</div>
like image 177
Poul Kruijt Avatar answered Jan 14 '23 00:01

Poul Kruijt


you can use document.dir in your app component contractor and it will set the dir to your html tag and can pass it with variable

direction : string = "rtl";
constructor() {
  document.dir = this.direction;
} 
like image 21
Ayman Ali Avatar answered Jan 13 '23 22:01

Ayman Ali