簡體   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