Interpolation within ngStyle allows dynamic styling to be applied in

When creating a column component for use within a grid in Angular, I am struggling with implementing a media query using ngStyle. Here is what my code looks like so far:

import { Component, Input } from '@angular/core'

const smMin = '48em'
const mdMin = '64em'
const lgMin = '75em'

const halfGutterWidth = '0.5rem'

@Component({
  selector: 'fg-col',
  template: `<div [ngStyle]="{
    mediaQuery {
      box-sizing: border-box;
      flex: 0 0 auto;
      padding-right: 0.5rem;
      padding-left: 0.5rem;
      flex-basis: flexBasis,
      max-width: flexBasis
    }
  }">
    <ng-content></ng-content>
  </div>`
})

let TargetDevice = 'phone' | 'tablet' | 'desktop'
let ColumnSize = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12

export class Column {
  @Input
  columnSize: ColumnSize =  1;

  @Input
  targetDevice: TargetDevice = 'phone';

  get mediaQuery() {
    const mq = {
      phone: `@media only screen and (min-width: ${smMin})`,
      tablet: `@media only screen and (min-width: ${mdMin})`,
      desktop: `@media only screen and (min-width: ${lgMin})`
    }
    return mq[this.targetDevice];
  }

  get flexBasis() {
    const baseWidth = 100 / TOTAL_COLUMNS
    const flexBasisNum = baseWidth * columnSize
    return `${flexBasisNum}%`
  }
 }

An error is appearing in the browser console as follows:

zone.js:516 Unhandled Promise rejection: Template parse errors:
Parser Error: Missing expected : at column 18 in [{
    mediaQuery {
      'box-sizing': 'border-box',
      flex: '0 0 auto',
      'padding-right': '0.5rem',
      'padding-left': '0.5rem',
      'flex-basis': flexBasis,
      'max-width': flexBasis
    }
  }] in Column@0:5 ("<div [ERROR ->][ngStyle]="{
    mediaQuery {
      'box-sizing': 'border-box',
"): Column@0:5
Parser Error: Unexpected token } at column 207 in [{
    mediaQuery {
      'box-sizing': 'border-box',
      flex: '0 0 auto',
      'padding-right': '0.5rem',
      'padding-left': '0.5rem',
      'flex-basis': flexBasis,
      'max-width': flexBasis
    }
  }

Answer №1

To dynamically set a field based on screen orientation, you can utilize window.matchMedia().

constructor() {
  var mql = window.matchMedia("(orientation: portrait)");
  mql.addListener(this.handleOrientationChange.bind(this));
  this.handleOrientationChange(mql);
}

isPortrait:boolean = false;
handleOrientationChange(mql) {
  this.isPortrait = mql.matches
}

You can then apply styles conditionally using ngStyle:

<div [ngStyle]="isPortrait ? { /* portrait styles here */ } : { /* landscape styles here */ }

For more information, refer to:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

establishing the position of the mouse cursor within a scaled div container

Issue at Hand: I'm encountering an obstacle with a transformed div set up as follows: $('#container').css('-moz-transform-origin', '0 0'); $('#container').css('-webkit-transform-origin', '0 0&ap ...

Is the hardware acceleration of the iPhone 4 significantly weaker than that of the iPhone 4s?

My HTML5 web application utilizes hardware acceleration through the CSS3 property translateZ(0). Everything runs smoothly on my 4s device. However, when I try the same application on an iPhone4, the performance drastically decreases and becomes almost un ...

Constantly receiving an undefined value when trying to access a variable in an ngrx Observable

Here is the code snippet I am working with: language.component.ts form: FormGroup; first: AbstractControl; second: AbstractControl; constructor(private _fb: FormBuilder) { this.first = new FormControl('', [Validators.required, Va ...

The attribute 'finally' is not found on the data type 'Promise<void>'

I've been attempting to implement the finally method on a promise but continue running into this issue. Property 'finally' does not exist on type 'Promise<void>'. After researching similar problems, I found suggestions to a ...

Discover the process of transitioning your animations from Angular to CSS

I have successfully implemented a fade-in/out animation using @angular/animation, but now I am looking to transfer this animation to CSS and eliminate the dependency on @angular/animation. Here is my current animation setup (triggering it with [@fadeInOut ...

What could be causing this addEventListener to fail when I am assigning elements to a class?

I've encountered an issue with my code where I have two text inputs and two date inputs. I tried to select all of them using QuerySelectorAll with a class, added a click listener that should change the textContent of a div element to "", but it's ...

Heroku deployment of rails application is failing to recognize CSS

Having faced the same issue time and time again, I am reaching out for help. I have exhausted all possible solutions, but my heroku app at still lacks proper CSS styling. Here is a snippet from my gemfile: source 'https://rubygems.org' # Bundl ...

Date Polyfill with Internationalization API in Angular 4/Angular-cli is not functioning as expected

I am struggling to make the polyfill of the Internationalization API work properly. The documentation (https://angular.io/docs/ts/latest/guide/pipes.html) states that all you need to do is add a script to your index.html: <script src="https://cdn.poly ...

What is the process behind the creation of the class or id fields in HTML for Gmail and Quora? How are these

When using Gmail: <tr class="zA yO" id=":1t4"> While on Quora: <span id="ld_zpQ1Cb_27965"> What is the purpose behind this and what specific tool do they employ to achieve it? ...

Selecting the initial item of every nested tag repeatedly for a total of n times

Is there a way to stop coloring elements after 'tue 7-1-1' using CSS? I am only allowed to manipulate the first child of every element up until a certain point through CSS, without modifying the existing code. Note: Span elements are nested wit ...

When the nestjs interface appears to be missing a defined method

Upon reviewing the code at this link: https://github.com/nestjs/nest/tree/master/packages/common One can see that the interface ArgumentsHost has been defined, but the contents of its methods are not explicitly defined. However, when looking at the foll ...

Encountering Compilation Error When Using RxJS Observable with Angular 6 and Swagger Codegen

Encountering TypeScript compiler errors related to rxjs while working with Angular 6 and Swagger Codegen: Cannot find module 'rxjs-compat/Observable' Referenced the following link for assistance: https://github.com/ReactiveX/rxjs/blob/master/M ...

What is the best way to bundle my Language Server along with my client?

Currently, I am in the process of developing a language server for VSCode which consists of both a client and a server that communicate over RPC. Fortunately, the official documentation includes a fully functional example, where the language server is div ...

Retrieve the 90 days leading up to the current date using JavaScript

I've been searching for a way to create an array of the 90 days before today, but I haven't found a solution on StackOverflow or Google. const now = new Date(); const daysBefore = now.setDate(priorDate.getDate() - 90); The result I'm looki ...

The Bootstrap 4 carousel link takes precedence over any other links on the page

Is anyone else experiencing this issue? I have three different link colors. .custom-links > a, a:link, a:hover, a:visited { color: black; } .carousel-caption > a, a:link, a:hover, a:visited, a:active { color: white; } .rss-links > a, a: ...

Rotating an image as it approaches the footer: a step-by-step guide

I'm trying to add a navigation arrow on my website that will rotate to point to the top when it reaches the footer. When clicked on, it should scroll back up to the top. The arrow already has a scrolling effect, but I need help figuring out how to m ...

JQuery hover effect for dynamically added elements

Currently, I am working on a webpage that will trigger an ajax call upon loading. The response data in JSON format will be processed and the elements will then be added to the DOM as shown below: $.ajax({ type: 'POST', url: "http://mysite.de ...

React TypeScript: Ensuring Accurate Typing for Dynamic Paths

Here is an example of what the router looks like: import { BrowserRouter, Route, Switch } from 'react-router-dom'; ... <Route exact path='/confirm-email/:confirmationCode' component={ConfirmEmail} /> ...

Angular 5 dynamically updates its model after the completion of events

The issue at hand Currently, I am working with angular 5 and have created a component that consists of 3 controls. <ss-multiselect-dropdown id="type" formControlName="type" (ngModelChange)="onChange('type')"></ss-multiselect-dropdown&g ...

Modify certain parameters in the current route using Angular 6 router

Within my Angular 6 setup, the URLs are structured as follows: /{language}/{app_section}/{object_id}/{view}?queryparams... All sections of the application utilize a language selector component, which is included in the template of a parent route to ensur ...