2017-10-14 60 views
0

我想知道是否可以通過angular的@component對象的'styles'屬性設置組件的樣式。Angular 4 - 帶變量的造型組件

下面是我試圖實現的一個示例,請注意'styles'屬性中的{{ratio}}變量。

@Component({ 
selector: 'img-thumb', 
templateUrl: './img-thumb.component.html', 
styleUrls: ['./img-thumb.component.css'], 
styles: [` 
    :host:after{ 
    content: ''; 
    display: block; 
    padding-bottom: {{ratio}}; 
    } 
`], 
host: { 
    '[style.height.px]' : 'height', 
    '[style.padding.px]' : 'gap' 
} 
}) 

export class ImgThumbComponent implements OnInit { 

@Input() height : any 
@Input() gap : any 
@Input() ratio : any 

//More code... 

} 

基本上我試圖實現:在一個變量的主機之後。 如果可能的話,我更喜歡在組件的.ts文件中實現它。

+0

插值語法* *僅適用於模板,不適用於樣式。 – jonrsharpe

+0

@jonrsharpe感謝您的快速回答。我使用插值語法來演示我試圖達到的目標。 –

+0

你有權訪問img-thumb.component.html文件嗎?如果您對修改該文件感到滿意,我會使用'[ngStyle]'屬性綁定語法直接在HTML元素上使用@input變量的值。 – Treeindev

回答

0

由於無法添加內聯僞元素樣式,因此一種解決方法是使用Angular的renderer2方法創建新的<style>標籤並在運行時將其附加到DOM。這裏有一個組件:

import { Component, ElementRef, ViewChild, OnInit, Renderer2 } from '@angular/core'; 

@Component({ 
    selector: 'app-component', 
    template: '<div #stylesContainer></div>' 
}) 
export class singleComp implements OnInit{ 
    // Get destination container 
    @ViewChild("stylesContainer") private stylesDist: ElementRef; 

    // Define variable values 
    height: string = "150px"; 
    gap: string = "30px"; 
    ratio: string = "10px"; 

    // Create the actual CSS style and store it in variables 
    styleClass = ".class{ height: "+this.height+"; padding: "+this.gap+"}"; 
    pseudoStyle = ".class:after{content: '';display: block;padding-bottom: "+this.ratio+"}"; 

    constructor(private renderer: Renderer2) {} 

    ngOnInit() { 
     // Dynamically create the CSS tags 
     const classStyle = this.renderer.createText(this.styleClass); 
     const pseudoElementStyle = this.renderer.createText(this.pseudoStyle); 

     // Insert the previously defined style into a new <style> element 
     const newStyleElement = this.renderer.createElement('style'); 
     this.renderer.appendChild(newStyleElement, classStyle); 
     this.renderer.appendChild(newStyleElement, pseudoElementStyle); 
     this.renderer.appendChild(this.stylesDist.nativeElement, newStyleElement); 
    } 
} 

在組件中的變量heightgapratio是硬編碼的上面,但你可以通過@input得到它們。 HTML模板包含div,本地參考#stylesContainer這將成爲動態追加樣式的目標元素。

當組件初始化時,它會生成一個新的<style>標籤,其中包含動態樣式,包括僞元素。然後使用Angular的Renderer2,它將新的<style>標籤附加到<div #stylesContainer>中,您可以使用這些標籤。@ViewChild

+0

嗨,非常感謝您的時間,真誠感謝您。 你的解決方案解決了這個問題,但是,它在組件中創建了一個全新的html,包含我的index.html所有的依賴關係。 這會導致兩個主要問題: 1.由於我在整個應用程序中使用這個組件很多,它會非常嚴重地影響性能。 2.創建的html擁有自己的頭部和身體標籤,根據我公司的一些同事的說法,這可能是一個SEO問題。 –

+0

它不應該在裏面創建一個新的整體html,而只需創建一個新的'