简体   繁体   中英

angular 2+ Trying to bind Input parameter in NgStyle

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM