【问题标题】:angular 2+ Trying to bind Input parameter in NgStyleangular 2+ 尝试在 NgStyle 中绑定输入参数
【发布时间】:2018-03-19 04:51:28
【问题描述】:

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

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

我有点难以理解绑定,所以我尝试了:

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

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

这必须很简单,并且可能有助于消除我对绑定工作原理的误解。 提前致谢, 修行者

【问题讨论】:

  • 这太棒了。他们都工作。我知道它必须很简单。我正在阅读书籍并参加在线课程,试图更熟悉这些概念。我想将您的答案标记为已接受,但我不知道如何。

标签: javascript html css angular binding


【解决方案1】:

你的错误在这一行:

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

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

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

[style.height]="height"

【讨论】:

    猜你喜欢
    • 2020-08-12
    • 1970-01-01
    • 2020-03-22
    • 2017-07-06
    • 1970-01-01
    • 2016-10-01
    • 1970-01-01
    • 2016-08-16
    • 2016-07-14
    相关资源
    最近更新 更多