Search code examples
htmlangulardomangular-material2angular-cdk

How to change dir property of the Angular CDK overlay at runtime?


I'm using Angular 10, on click the following function is executed to preform direction change:

private changeHtmlDirection(direction: 'rtl' | 'ltr') {
    document.getElementsByTagName("html")[0].dir = direction;
}

It works well, only that the Angular CDK does not update.

I tried to find an API to change Angular CDK's direction at runtime, but couldn't find any. I saw that there's a BidiModule but it uses only to get the current direction rather than set it.

Is there any solution?

enter image description here


Solution

  • According to the material documentation, you can't change 'dir' on the "html" tag so that affects bidi API. You can see the document at the following link: bi-directionality document

    But if you want to use material bi-directionality you can add the 'dir' directive to a container element in the root component like bellow:

    <div [dir]="documentDirection"> </div>
    

    and whenever the 'documentDirection' variable changes, the bidi "change emitter" will be emit. like following code you can subscribe to it:

    constructor(
    private dir: Directionality ) {
    this.isRtl = dir.value === 'rtl';
     this.dir.change.subscribe(() => {
      this.isRtl = !this.isRtl;
     });
    

    }