3

I have designed a shape and I want to determine its height based on a TypeScript-function, but the ngStyle does not apply the height to the shape.

HTML:

<div class = "card" [ngStyle] = "{'height': CalculateHeight()}" (click) = 'onSelect()'>

Function:

CalculateHeight(): number {
  let CardHeight = ((this.Card.duration.Hours * 60) +
    (this.Card.duration.Minutes)) * 2;

  if (CardHeight <= 60) {
    CardHeight = 60;
  }

  console.log(CardHeight);

  return CardHeight;
}

What is the problem?

Tony Ngo
  • 19,166
  • 4
  • 38
  • 60
lydal
  • 802
  • 3
  • 15
  • 33
  • Hi @Dorian, as you can see there ar several answers to your question. Please mark as the right answer, if someone solved your issue. To lean more about how Stack Overflow works, [take the tour](https://stackoverflow.com/tour). – jsadev.net Jul 24 '19 at 05:49

3 Answers3

10

CalculateHeight returns just a number. But height to work properly, there need to be the unit as well.

Try the following line.

< div class = "card" [ngStyle] = "{'height.px': CalculateHeight()}" (click) = 'onSelect()' >

Note the .px. It will do the trick.

OR. you can make CalculateHeight to return a string with the height unit attached at the end. For example 400px.

Johna
  • 1,836
  • 2
  • 18
  • 29
3

You will also need px in your html file like this

<div class="card" [ngStyle]="{'height': CalculateHeight() + 'px'}" (click)="onSelect()">
Tony Ngo
  • 19,166
  • 4
  • 38
  • 60
1

The problem is that you don't set any unit to your height.. its like "300 what?, eggs?, cars?, pixels?" :P

Just return your result with a valid unit. This could simply be done by adding + 'px' to your returned value:

CalculateHeight(): number {
  let CardHeight = ((this.Card.duration.Hours * 60) +
    (this.Card.duration.Minutes)) * 2;

  if (CardHeight <= 60) {
    CardHeight = 60;
  }

  console.log(CardHeight);

  return CardHeight + 'px';
}

You should also change your HTML from (click)='onSelect()' to (click)="onSelect()" because its recommend to use doublequotes instead of singlequotes, when quoting attributes values.

To learn more take a look at the recommend style-rules, especialy for HTML Quotation Marks.

jsadev.net
  • 2,800
  • 1
  • 16
  • 28