【问题标题】:Interpolation within ngStylengStyle 中的插值
【发布时间】:2017-02-28 15:03:52
【问题描述】:

在构建在grid 中使用的列组件时,我需要使用带有ngStyle 的媒体查询。这是我目前所拥有的:

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}%`
  }
 }

浏览器控制台中的错误如下所示:

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
    }
  }

【问题讨论】:

  • 那么……会发生什么?另外,你知道| 是做什么的吗?它们是作业,而不是打字。
  • @jonrsharpe 我想为我的属性创建一个基于字符串的枚举。我添加了错误,这是 mediaquery 的模板解析问题

标签: css angular typescript media-queries ng-style


【解决方案1】:

可以使用window.matchMedia()设置字段

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

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

然后参考ngStyle中的公寓

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

另见

【讨论】:

  • 我希望像使用 here 那样使用 aphrodite 或 glamor 进行内联样式。
  • 对不起,不知道。
猜你喜欢
  • 2019-11-26
  • 1970-01-01
  • 2018-11-20
  • 2017-11-17
  • 2019-06-11
  • 2017-09-21
  • 2017-11-30
  • 2016-07-14
  • 2017-12-15
相关资源
最近更新 更多