Tips for changing the color of an icon when clicking a button

How can I dynamically change the color of an icon when clicked?

Would using ngClass be the most efficient approach for this task?

Currently, I have assigned a class to my icon.

<ion-card>
    <ion-row>
        <ion-col>
            <button ion-button icon-left clear small>
                <ion-icon name="eye" #name [ngClass]="{
                'isActive' : isActive}" (click)="activeCheck(name)">
                </ion-icon>
            </button>
        </ion-col>
    </ion-row>
</ion-card>

.ts file

export class NewsPage implements OnInit {
    isActive: boolean = false;

    activeCheck(name) {
        console.log(name);
        this.isActive = !this.isActive;
    }
}

Answer №1

To enhance the appearance of an activated class, you can utilize the following code snippet. The ngClass directive dynamically adds a class based on the value of the isActive variable. Instead of using a function call, you can trigger a change in the isActive value by using (click).

<ion-icon name="eye" #name [ngClass]="isActive ? 'activated' : ''" (click)="isActive = !isActive">
</ion-icon>

Answer №2

No need to create a separate function for this task. You can easily switch the value of the isActive property directly in the template.

Remember to attach the (click) event handler to the button element rather than the ion-icon.

For a more concise syntax, utilize [class.isActive]="isActive".

Check out the code example below:

<ion-row>
  <ion-col>
    <button 
      ion-button 
      icon-left 
      clear 
      small 
      (click)="isActive = !isActive">
      <i 
        name="eye" 
        #name 
        [class.isActive]="isActive">
      </i>
    </button>
  </ion-col>
</ion-row>

Visit this Live StackBlitz Example for further reference.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Improprove the performance of an array of objects using JavaScript

Hello there, I am currently in the process of creating an array. this.data = [{ label: 'Total', count: details.request.length, }, { label: 'In-Progress', count: details.request.filter((obj) => obj.statusId === 0 || ob ...

What is the best way to upload a file using a relative path in Playwright with TypeScript?

Trying to figure out how to upload a file in a TypeScript test using Playwright. const fileWithPath = './abc.jpg'; const [fileChooser] = await Promise.all([ page.waitForEvent('filechooser'), page.getByRole('button' ...

The issue with Angular's mat-icon not displaying SVGs masked is currently being investigated

I have a collection of .svgs that I exported from Sketch (refer to the sample below). These icons are registered in the MatIconRegistry and displayed using the mat-icon component. However, I've observed issues with icons that utilize masks in Sketch ...

Identify all the CHECKBOX elements that are visible and not concealed

On my page, I have various checkboxes - some with hidden=true and others with hidden=false attributes. Despite trying to use a selector or jQuery to locate checkboxes with the hidden property, I am still facing some challenges. My goal is to differentiate ...

Challenges with using forRoot and other function calls in AOT compilation

Upon compiling my app, I am faced with the error message: "Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, resolving symbol Declaran ...

Is there a method to add columns to an Angular material table dynamically?

I'm encountering an issue with creating dynamic tables using Angular Material tables. Since the table is reliant on an interface, I have a set number of columns. What I'm aiming for is to generate a table dynamically based on the server's re ...

The Angular/Typescript framework encountered an issue when trying to locate a differ that can handle an object of type 'object'. NgFor is limited to binding with Iterables like Arrays and is not compatible with plain objects

I am currently utilizing Angular for my project. I am attempting to call an API to fetch data from it, but I keep encountering this error: core.js:4352 ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object&ap ...

Issue: The --outFile flag only supports 'amd' and 'system' modules

Encountering an issue while trying to compile an Angular project in Visual Studio Code using ng build and then serving it with ng serve Unfortunately, faced the following error message in both cases: The error 'Only 'amd' and 'syste ...

Encountering an issue with Angular where all parameters for NgZone cannot be resolved

Currently, I am in the process of learning Angular and experimenting with the Firebase Authentication services. However, every time I try to load the component that utilizes this service, I encounter an error. Error: Can't resolve all parameters for N ...

Using Ionic2 to connect with PHP server APIs

I am fairly new to working with ionic, although I have a basic understanding of angular2. My goal is to access an API created in PHP using the combination of ionic2 and angular2. feed.php header('Access-Control-Allow-Origin: *'); $db_ ...

How to Access Static Method from Non-Static Method in TypeScript

Within my hierarchy, there is some static content present in all levels (for example, the _image). It would be ideal to access the corresponding _image without repeating code: Here's what I envision: class Actor { static _image; // Needs to be s ...

Personalize the Legend of a Pie Chart with chart.js

My current setup involves using the ChartModule in PrimeNG, which is powered by Chart.js. The issue I'm facing is with a pie chart that displays different types of data, one of which is deliveries. Sometimes there are multiple instances of deliveries ...

Is the @Output decorator with EventEmitter functioning properly for sibling components inside <router-outlet>?

Code Snippet from app.component.html <router-outlet> <app-header (cartRefresh)="updateCart(user_id)"></app-header> <app-breadcrumb></app-breadcrumb> </router-outlet> <app-footer></app-footer> Pull Cart Func ...

Incorporating the unshift method in JavaScript: A Step-by-

I'm looking to create a new function with the following requirements: Function add(arr,...newVal){ } array = [1,2,3]; add(array,0) console.log(array); //I want this to output [0,1,2,3] I tried creating the function similar to push like this: ...

Tips for importing a .geojson document in TypeScript using webpack?

I am trying to extract data from a .geojson file but faced some challenges while attempting two different methods: const geojson = require('../../assets/mygeojson.geojson'); The first method resulted in an error message stating: Module parse f ...

Issue with Jhipster4 when trying to generate an Angular 2 app

After utilizing jhipster4 to create my application, I noticed it consists of a client side and a server side. However, when running ./mvnw from the application's root directory, only the server is built, without the client. Here is the structure of my ...

Cookie authentication in CodeIgniter with Angular HTTP requests in Ionic 3

I am experiencing difficulties sending POST/get requests to the server. When using the Postman Chrome extension, everything works fine. However, when attempting to use Angular Http (not HttpClient) in Ionic, I encounter errors. The first error is related t ...

Using Material UI with React and TypeScript

I need some assistance with organizing my menus correctly in React using TypeScript. Currently, they are displaying on top of each other instead of within their respective category menus. I have been struggling to find a solution and would appreciate any h ...

Gatsby website failing to create slugs as anticipated

While trying to follow the Gatsby tutorial, I ran into an issue with generating slugs for MDX files in a subdirectory of src/pages. For instance, if I have a file like src/pages/projects/devmarks/index.md, the expected slug according to the tutorial should ...

The installation of @types/jquery leads to an unnecessary global declaration of $

In my package.json file, I have the following dependencies defined: { "dependencies": { "@types/jquery": "^3.5.5", } } This adds type declarations through @types/jquery/misc.d.ts, including: declare const jQuery: JQue ...