繁体   English   中英

angular 2+ 尝试在 NgStyle 中绑定输入参数

[英]angular 2+ Trying to bind Input parameter in NgStyle

问题:我想要一个宽度为 100% 和高度的单个组件(间隔器),它可以在 HTML 中出现的任何位置输入(本测试中的 home.html):

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

间隔器.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;
}

间隔.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 给出: height 是 '200px' 但红色边框框的高度刚好足以容纳 'spacer is here' 文本。

我很难理解绑定,所以我尝试过:

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

控制台:高度是 200 像素,我认为它可以工作但没有变化。 不理解 attr,我尝试了 attr.height 的变体。

这必须很容易,并且可能有助于消除我对绑定如何工作的误解。 提前致谢,瑜伽士

你的错误位于这一行:

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

您将高度绑定到字符串'height'但您应该将其绑定到组件的height属性,例如:

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

或者

[style.height]="height"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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