Home > Article > Web Front-end > Detailed explanation of several ways to add css classes to HTML elements in angular
This article will introduce to you several ways to add css classes to HTML elements in angular. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Mainly explores several implementations of dynamically adding classes to HTML elements in Angular, including the use of the className directive, the use of NgClass, etc. [Related recommendations: "angular tutorial"]
The main code is:
let element = document.getElementById('exampleTarget'); element.className = 'additional-class'
A more specific explanation is in the usage of className, so I won’t go into details here.
You can simply use className
to bind the class to our HTML element :
<div [className]="'example-class'"> </div>
Of course, it doesn’t make much sense to use this attribute to bind static classes. We can bind related classes according to conditions:
<div [className]="condition ? 'condition-true-example-class': 'false-example-class'"> </div>
In condition
is# When it is ##true, the
condition-true-example-class class will be added, and when it is
false, the
false-example-class class will be added. .
<div [className]="'example-class' + variableValue"> </div>
<div [className]="condition ? 'condition-true-example':''"> </div>is neither beautiful nor easy to understand. We can use:
<div [class.example-class]="condition"> </div>to achieve the above requirements.
ngClass.
ngClass directive to complete the above two examples:
<!-- 替代 className 属性绑定 --> <div [ngClass]="{ 'condition-true-example-class': condition, 'false-example-class': !condition }"> </div> <!-- 替代基于条件切换 class --> <div [ngClass]="{'example-class': condition}"> </div>In addition to the above methods,
ngClass There are some other commonly used Method:
<!-- 添加单个类 --> <div [ngClass]="'example-class'"> </div> <!-- 添加多个类 --> <div [ngClass]="['example-class','example-class-2']"> </div>For more usage methods, please check:
It should be noted that:
If in the component UseHostBinding in the
ts file to add multiple classes:
export class AppExampleComponent implements OnInit { @HostBinding('class') className = 'example-basic-class cursor-pointer d-inline-flex align-items-center'; // ... }Then when using it, you cannot pass
class,
className,
ngClass, add a class.
Introduction to Programming! !
The above is the detailed content of Detailed explanation of several ways to add css classes to HTML elements in angular. For more information, please follow other related articles on the PHP Chinese website!