簡體   English   中英

將HTML img屬性設置為Angular綁定

[英]Set HTML img attribute to Angular binding

在我的Angular組件的HTML類中,我有一個顯示的圖像:

<div class="row" id="work">
  <div class="col-xl-3 col-lg-4 col-md-6 col-sm-12" id="">
      <img class="img-fluid" width="100%" [height]="height" src="assets/images/logo.png" alt="">
      <img class="img-fluid" width="100%" height="100" src="assets/images/logo.png" alt="">
      <img class="img-fluid" width="100%" height="100" src="assets/images/logo.png" alt="">
  </div>
</div>

在我的組件的打字稿文件中,我在init上將高度變量設置為“100”。

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  height = "500";

  constructor() { }

  ngOnInit() {
    this.height = "500";
  }
}

在頁面加載時,圖像高度等於默認圖像高度,它不讀取/使用我的高度變量。 可能是傻事,但不確定是什么。

編輯:

“img-fluid”就是問題所在。 它忽略了height屬性,將height設置為auto,所以我無法自己從Typescript中設置它。

試試這樣

<img class="img-fluid" width="100%" height="{{height}}" src="assets/images/logo.png" alt="">

@penleychan是正確的,只需在大括號中包裝高度並引用高度變量作為其值。 但為了澄清為什么你的工作不正常,你只是缺少周圍的引號:

height="{{height}}"

如果我沒有弄錯的話,添加引號會讓你的工作也一樣。 但@ penleychan的方法更常見。

只是用

[ngStyle]='{height:height}'

編輯

或者像這樣使用:這里'x'是條件(如果有的話),“200px”是默認高度。 [ngStyle]='{height : x ? "200px" :height}'

“img-fluid”標簽就是問題所在。 它忽略了height屬性,將height設置為auto,所以我無法使用Typescript自行設置它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM