简体   繁体   English

在 angular10 中添加 class 以及 angular ts 文件中的样式属性

[英]Add class along with style properties from angular ts file in angular10

I have to add a class to a div on a button click along with a height property in that class.我必须在按钮单击时将 class 添加到 div 以及 class 中的 height 属性。 The class will have a property height which is calculated dynamically everytime depending upon the height of the div. class 将具有一个属性高度,该高度每次根据 div 的高度动态计算。 I don't want to add style attribute to my div element.我不想将样式属性添加到我的 div 元素。 I want to add a class with height property.我想添加一个具有高度属性的 class 。

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:如果 NgClass 不是一个选项,因为您希望 class 是动态的,您可以在组件 ts 文件中编写 function ,如下所示:

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

and in then html file然后在 html 文件中

<div [ngStyle]="getStyles()"></div>

you can use a custom attribute directive: https://angular.io/guide/attribute-directives您可以使用自定义属性指令: https://angular.io/guide/attribute-directives

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM