2

In my app I'm going to add or remove a class based on the device orientation. So if the app is portrait things would remain as it is. If it's landscape, then a class should get added.

I know I can easily do this with [class.ClassName] -

<div class="parentclass" [class.landscapeClass]="makeTrue">
 <span></span>
</div>

But the problem is I will have to repeat this change in several templates.

How can I can easily add and remove a class (landscapeClass in my example) wherever another class (parentclass) is used? And remove it when the app is portrait.

I'm getting the orientation of the app using the cordova screen orientation plugin.

I'm using Angular2 RC4 and I'm looking for solution without having to use Jquery.

EDIT: The reason I'm trying to find a solution like this is because using media queries messes up my UI when the keyboard comes up on Android. I'm aware of the work around using aspect-ratio but it's not a 100% reliable solution.

user3607282
  • 2,465
  • 5
  • 31
  • 61
  • What does "wherever another class (parentclass) is used?" mean? If a class is added somewhere on a parent element, then do ...? I don't think there is a way, at least not a feasible one. – Günter Zöchbauer Sep 07 '16 at 10:47
  • Hi @GünterZöchbauer. What I mean is if the device is landscape, wherever the class "parentClass" is used, the class "landscapeClass" should get added. So in landscape it would be
    . When it's portrait
    – user3607282 Sep 07 '16 at 10:52

1 Answers1

2

If the class is only there to adjust the styling of the elements, you can use css media queries to check for portrait orientation instead of adding a class.

@media only screen and (orientation: portrait) {}
@media only screen and (orientation: landscape) {}

EDIT: You can also put the class on a more global element and begin your selectors with the orientation glass.

CSS:

.orientationPortrait .parentClass { /* styling */}

Sass:

.parentClass {
  .orientationPortrait & { /* styling */}
}
  • The reason I'm trying to set styles by adding a class is because the media queries are messing up mu UI when the keyboard comes up on Android. :( Sorry. I should mention it in my question. – user3607282 Sep 07 '16 at 10:57
  • I've found a question dealing with that issue here: http://stackoverflow.com/questions/8883163/css-media-query-soft-keyboard-breaks-css-orientation-rules-alternative-solut – DisplayName Sep 07 '16 at 11:01
  • Yeah. But they say it doesn't work for all mobile devices. :( I need a solution where I can be a 100% sure. – user3607282 Sep 07 '16 at 11:03
  • You could then approach it differently: Only add the class once on a more global element.Then in your selectors simply start with the orientation class. Eg CSS: .orientationPortrait .parentClass { /* styling */ } – DisplayName Sep 07 '16 at 11:12
  • Yeah that makes sense. Can you add it as an edit to your answer so I can mark it :) – user3607282 Sep 07 '16 at 11:23