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?
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>
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With