2017-10-07 51 views
1

問題:我想要一個寬度爲100%的單個組件(spacer),並且可以在HTML中顯示的任何位置輸入高度(此測試中的home.html) :angular 2+試圖綁定NgStyle中的輸入參數

number 1 
    <spacer height="'200px'"></spacer> 
    no more 

的spacer.html:

<div class="container-fluid spaceContainer" [ngStyle]="{'height': 'height'}"> 
    spacer is here <<<--- this text is just for testing 
</div> 

的SCSS:

.spaceContainer { 
    width: 100%; 
    border: 1px solid red; 
    display: flex; 
    flex-direction: row; 
} 

Spacer.ts:

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

@Component({ 
    selector: 'spacer', 
    templateUrl: './spacer.component.html', 
    styleUrls: ['./spacer.component.scss'] 
}) 
export class SpacerComponent implements OnInit { 
    @Input() height: string; 

    constructor() { 
    } 

    ngOnInit() { 
    console.log('height is '+ this.height); 
    } 
} 

當它運行時,將執行console.log給出:高度「爲200px」 但紅色邊框盒子的高度剛好足以容納「間隔是這裏的文字。

我很難理解,結合了一點,所以我嘗試:

<spacer height="200px"></spacer> 

控制檯:高度爲200像素,而且我認爲他的工作,但沒有任何變化。不理解attr,我嘗試了attr.height的變種。

這很容易,可能有助於消除我對如何綁定工作的誤解。 由於提前, 瑜珈

+0

這太棒了。他們都工作。我知道這一定很簡單。我正在閱讀書籍並參加在線課程,試圖讓這些概念更加舒適。我想標記你的答案被接受,但我不知道如何。 –

回答

1

自己的錯誤位於這條線:

[ngStyle]="{'height': 'height'}" 
        ^^^^^^^^^^ 
       it should be just height 

你結合的高度,以字符串'height',但你應該把它綁定到你的組件類似height屬性:

[ngStyle]="{'height': height}">? 

[style.height]="height"