This article will introduce to you several ways to add css classes to HTML elements inangular. 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 ofclassName, so I won’t go into details here.
You can simply useclassName
to bind the class to our HTML element :
Of course, it doesn’t make much sense to use this attribute to bind static classes. We can bind related classes according to conditions:
Incondition
is# When it is ##true, the
condition-true-example-classclass will be added, and when it is
false, the
false-example-classclass will be added. .
ngClass.
ngClassdirective to complete the above two examples:
ngClassThere are some other commonly used Method:
It should be noted that:
If in the component UseHostBindingin the
tsfile to add multiple classes:
export class AppExampleComponent implements OnInit { @HostBinding('class') className = 'example-basic-class cursor-pointer d-inline-flex align-items-center'; // ... }
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!