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.
-
Take a look at this angular.io/api/common/NgClassRaffael– Raffael2022-02-03 07:48:53 +00:00Commented 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.gaurav gupta– gaurav gupta2022-02-03 07:58:24 +00:00Commented 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.Guvaliour– Guvaliour2022-02-03 08:27:05 +00:00Commented Feb 3, 2022 at 8:27
Add a comment
|
2 Answers
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>
1 Comment
gaurav gupta
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.