0

I have to add a class to a div on a button click along with a height property in that class. The class will have a property height which is calculated dynamically everytime depending upon the height of the div. I don't want to add style attribute to my div element. I want to add a class with height property.

3
  • Take a look at this angular.io/api/common/NgClass Commented Feb 3, 2022 at 7:48
  • @Raffael No ngClass will not work at my case. ngClass will add a class that is present in my scss file. I actually want to add a class and its properties from my angular componet.ts file. Commented Feb 3, 2022 at 7:58
  • You can only able to add dynamic style from TS. We can't dynamically update styles inside class of CSS file. If like you want to do calc in CSS refer this w3schools.com/cssref/func_calc.asp. Commented Feb 3, 2022 at 8:27

2 Answers 2

1

If NgClass is not an option as you want the class to be dynamic, you could write a function in your component ts file like this:

getStyles() {
  let calcHeight = .... // do the calcutions
  return {'height': calcHeight + 'px'};
}

and in then html file

<div [ngStyle]="getStyles()"></div>
Sign up to request clarification or add additional context in comments.

1 Comment

I tried this also. It adds a style attribute in my div. like <div style="height: 10px"></div>. Instead of this I want to add a class in my div like <div class="myClass"></div> and I want to set a property height in myClass from ts file only so that based on some calculations i can modify the height value.
0

you can use a custom attribute directive: https://angular.io/guide/attribute-directives

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.