Angular2材质sidenav-动态更改rtl/ltr方向
我正在尝试根据用户的语言选择动态更改布局,并即时从LTR切换到RTL.
I'm trying to change my layout dynamically according to users' language selection and switch from LTR to RTL on the fly.
我正在使用Angular 2 rc6,材料2.0.0-alpha.9-3
I'm using Angular 2 rc6, material 2.0.0-alpha.9-3
页面加载时看起来很像rtl或ltr. 但是,当从应用程序内部对其进行动态更改时(请参见plunker),方向会发生变化,但是生成的元素md-sidenav-content的计算的margin-right和margin-left的计算错误.
It looks like when the page is loaded, it works perfectly with either rtl or ltr. However, when it's changed dynamically from within the app (see plunker), the direction changes but the generated element md-sidenav-content has a miscalculated margin-right and margin-left.
进一步挖掘,我设法看到_dir对象具有一个eventEmitter,该事件应监视_dir的更改事件并重新计算边距
Digging further, I managed to see that the _dir object has an eventEmitter that should watch for on change events of _dir and recalculate the margins
@ angular/material/sidenav/sidenav.js:
@angular/material/sidenav/sidenav.js:
_dir.dirChange.subscribe(function () { return _this._validateDrawers(); });
但是在动态更改方向时永远不会调用它. 虽然,_dir首次加载页面时保留正确的值,无论是ltr还是rtl.
But it's never called when changing the direction dynamically. Although, _dir holds the correct value when page is being loaded for the first time, whether its ltr or rtl.
最后,这是一个用来证明这种行为的工具:
Finally, here's a plunker to demonstrate the behaviour:
http://plnkr.co/edit/o8lXWC?p=preview
我怀疑我没有正确使用_dir,但是无法弄清楚什么是正确的方法.
I suspect I'm not using _dir correctly but not managed to figure out what's the right way to do it.
看看源代码Dir
指令
@Input('dir') _dir: LayoutDirection = 'ltr';
-
- https://github.com/angular/material2/blob/2.0.0-alpha.9/src/lib/core/rtl/dir.ts#L19-L43
如您所见,您正在更改
_dir
属性,而不是dir
设置器:As you can see you're changing
_dir
property instead ofdir
setter:set dir(v: LayoutDirection) { let old = this._dir; this._dir = v; if (old != this._dir) { this.dirChange.emit(null); } }
所以我认为您的解决方案应该是:
So i think your solution should be like:
视图
<md-sidenav-layout fullscreen dir="ltr" #root="$implicit"> <select #langSelect (change)="changeLang(langSelect.value, root)">
组件
changeLang(lang, root: Dir) { this.translate.use(lang); root.dir = lang == "fr" ? "rtl" : "ltr"; }
这样,您可以在组件上省略
direction: string
属性.This way you can omit
direction: string
property on your component.还有一个音符:
translate: TranslateService; //it's redundant `private translate: TranslateService` does it direction: string; // omit it constructor(private translate: TranslateService) { this.direction = "ltr"; // omit it translate.addLangs(["en", "fr"]); translate.setDefaultLang('en'); let browserLang = translate.getBrowserLang(); translate.use(browserLang.match(/en|fr/) ? browserLang : 'en'); this.translate = translate; // it's redundant }
这是您的 柱塞示例
Here's your Plunker Example
如果您认为这是错误的决定,请检查此
If you think that this is the wrong decision then check this
希望这对您有帮助!