The ngClass Directive
Explore how to use Angular's ngClass directive to dynamically apply CSS classes based on component properties. Learn to highlight active buttons and disable navigation controls conditionally, improving your app's interactivity. Understand applying objects or functions to ngClass for cleaner templates and effective styling control.
We'll cover the following...
We have a set of buttons for navigating through the images. They look great, but let’s make them more interactive. The buttons should change color if the corresponding image is in view. This will indicate which image a user is viewing.
Bootstrap comes with classes for changing the color of the buttons. They’re the active and disabled classes.
The active class
The active class will highlight the button in blue. If we want to apply this class, we’ll need to figure out which button to apply it to. We’ll keep track of which button to add the class to by creating a property in the app.component.ts file.
export class AppComponent {
activeImg = 0;
// Other code....
}
The value of the activeImg property will be the index of the button. We can update the loop in the app.component.html file ...