angular 2+试图绑定NgStyle中的输入参数

问题描述:

问题:我想要一个宽度为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

这太棒了。他们都工作。我知道这一定很简单。我正在阅读书籍并参加在线课程,试图让这些概念更加舒适。我想标记你的答案被接受,但我不知道如何。 –

自己的错误位于这条线:

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

你结合的高度,以字符串'height',但你应该把它绑定到你的组件类似height属性:

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

[style.height]="height"