Method of Changing the Image of a Button in Active and Inactive States, and Changing the Style of a Footer in Angular

angular button toggle footer bar style
01 December 2024

Brief Introduction to Angular and Style Changes

Angular is one of the most popular frameworks for web application development. One of its attractive features is the ability to manage data and view results in real time. One of the common needs in web development is changing the appearance of elements based on user interaction. For example, you may want to change the image of a button based on whether the button is active or in a specific state.

In this section, we will look at how to use Angular to manage the active and inactive states of a button and also change the style of a footer dynamically. This example is based on changes in user events and class management in CSS created using Angular.

Setting Up the Project

Before starting, make sure you have installed Node.js and Angular CLI. After that, create a new project and navigate to its directory.


  ng new buttonToggle
  cd buttonToggle
  

Sample Code


  <!-- app.component.html -->
<button (click)="toggleButton()" [ngClass]="{'active': isActive}">
<img [src]="isActive ? 'active-image.png' : 'inactive-image.png'" alt="Toggle Button">
</button>
<footer [ngStyle]="{'background-color': isActive ? '#333' : '#666'}">
Footer Content
</footer>

  // app.component.ts
  export class AppComponent {
isActive = false;
toggleButton() {
this.isActive = !this.isActive;
}
}

Line by Line Code Explanation

<button (click)="toggleButton()" [ngClass]="{'active': isActive}">
This button is clickable and its CSS class 'active' is assigned based on the state isActive.

<img [src]="isActive ? 'active-image.png' : 'inactive-image.png'" alt="Toggle Button">
The button image changes based on the state isActive: if true, it shows the active image, and if false, it shows the inactive image.

<footer [ngStyle]="{'background-color': isActive ? '#333' : '#666'}">
The style of the footer changes based on the state isActive. If active, it becomes darker, and if inactive, it becomes lighter.

export class AppComponent {...
Here we have a class managing the state of the button active/inactive.

toggleButton() {...
This function toggles the state of isActive. Each time the button is clicked, the value of isActive toggles.

FAQ

?

How can I change the state of a button in real time?

?

How can I apply CSS styles dynamically in Angular?

?

Can I use different images for active and inactive states?

?

How can I change CSS classes dynamically?