angular 2+ Trying to bind Input parameter in NgStyle

Viewed 1231

Problem: I want a single component (spacer) that will have width 100% and a height that can be input wherever it appears in the HTML (home.html in this test):

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

The spacer.html:

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

The 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);
  }
}

When it runs, the console.log gives: height is '200px' but the height of the red-bordered box is just enough to hold the 'spacer is here' text.

I struggle understanding binding a bit so I've tried:

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

Console: height is 200px, which I thought would work but no change. Not understanding attr, I tried variants of attr.height.

This has to be easy and may help clear up my misunderstanding of how binding works. Thanks in advance, Yogi

1 Answers

Your mistake is located at this line:

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

You're binding height to string 'height' but you should bind it to height property of your component something like:

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

or

[style.height]="height"
Related