2017-02-27 39 views
0

構建一個列組件供在grid中使用時,我需要使用帶有ngStyle的媒體查詢。這是我到目前爲止有: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 [email protected]:5 ("<div [ERROR ->][ngStyle]="{ 
    mediaQuery { 
     'box-sizing': 'border-box', 
"): [email protected]: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 
    } 
    } 
+0

看到這麼......會發生什麼?另外,你知道'|'做什麼嗎?他們是作業,而不是打字。 – jonrsharpe

+0

@jonrsharpe我想爲我的屬性創建一個基於字符串的枚舉。我已經添加了這個錯誤,這是一個與mediaquery – vamsiampolu

回答

2

您可以使用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 */ } 

+0

模板解析問題,我希望使用阿芙羅狄蒂或魅力的內聯樣式,因爲我[在這裏](https://github.com/vamsiampolu/flexboxgrid/) – vamsiampolu

+0

對不起,不知道那個。 –