Using Angular and TypeScript to update text and global color variable within a ngFor iteration

Within my ngFor loop, I have a toggle button for 'watching' and 'watch' on each feed item:

<button ion-button small icon-left [color]="primary" (click)="toggleNamedColor(feedItem)">
        {{feedItem.watchlist}}
</button>

The values for feedItem.watchlist are either false or true.

I am looking for the simplest way to update the global variable 'color' and display text based on the following conditions:

If feedItem.watchlist is false, change color to success and text to 'watching'. If feedItem.watchlist is true, change color to primary and text to 'watch'.

Any help or suggestions would be greatly appreciated. Thank you!

Answer №1

Utilizing Angular's [] notation in attributes enables the ability to dynamically assign attribute values by passing JavaScript expressions to the element.

One example of this concept can be seen below:

<button ion-button small icon-left [color]="feedItem.watchlist ? 'primary' : 'success'" (click)="toggleNamedColor(feedItem)">
        {{feedItem.watchlist}}
</button>

If the logic required for determining the value becomes too intricate, it is also possible to pass a function to handle the logic within the controller (or component).

<button ion-button small icon-left [color]="getButtonColor(feedItem.watchlist)" (click)="toggleNamedColor(feedItem)">
        {{feedItem.watchlist}}
</button>

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

Here are some steps to turn off browser autocomplete for a p-inputMask field

I need help in disabling the browser autocomplete on a field that uses p-inputMask. I have tried using autocomplete="nope" on other fields and it works perfectly, but for this specific case, it doesn't seem to work. Can anyone point out what I might b ...

Optimal method for populating table filter values from query string in Typescript while handling asynchronous calls

Using Typescript for Angular, I am dealing with a table that has filters in the form of drop downs. The data for each filter is retrieved asynchronously from the backend. My challenge is to load the data for all filters while setting default values based o ...

"Users have reported that the file upload preview feature in Angular 6 only works after the

I am currently utilizing Angular 6. In my application, I have a simple input type="file" field that passes data to an image source which displays the image I intend to upload. The issue I am facing is that when I select an image for the first time, nothi ...

Ways to Access HTTP Request Headers in Angular 6 upon Page Load

Is it possible to retrieve request header information in Angular 6/7 upon application initialization? I specifically require access to header values for security and access management purposes, as these values are set in the headers during the usage of th ...

Using Node.js and Typescript to bring in external modules from

Attempting to generate a random integer between 1 and 6 using the 'random' library. Here's what I have coded so far: import random from 'random' function rollDice(min:number, max:number) { return Math.floor(Math.random() * (ma ...

Display Bootstrap Modal using Typescript in Angular

Looking for some creative ideas here... My Angular site allows users to register for events by filling out a form. They can also register themselves and other people at the same time. https://i.sstatic.net/a44I7.png The current issue ~ when a user clicks ...

Arranging a dictionary by its keys using Ramda

My task involves manipulating an array of items (specifically, rooms) in a program. I need to filter the array based on a certain property (rooms with more than 10 seats), group them by another property (the area the room is in), store them in a dictionary ...

Tips for passing an object by value to an Angular2+ component

Imagine having a scenario where I create a component that takes a Foo instance and generates a form for editing. export class ChildComponent implements OnInit { @Input() foo : Foo; @Output() onChange : EventEmitter<Foo> = new EvenEmitter<Foo& ...

What is the correct way to add properties to an interface in TypeScript?

I have experience with styled-components "themes" and how they work by defining custom theme properties for TypeScript autocompletion within styled components. The process involves extending the DefaultTheme interface with our custom theme properties like ...

Using ngIf for binding

Trying to bind values based on conditions specified in *ngIf. However, when using the && operator within *ngIf, it seems to be behaving mysteriously. Sample Code: <div *ngIf="days.sunday == true"> <p class="circle ml-3" ...

The issue arises when Jest fails to align with a custom error type while utilizing dynamic imports

In my project, I have defined a custom error in a file named 'errors.ts': export class CustomError extends Error { constructor(message?: string) { super(message); Object.setPrototypeOf(this, Error.prototype); this.nam ...

Tips for conducting key down event testing on a material ui MenuList element utilizing react-testing-library

Looking to test the key down event on my MenuList component. Component: import MenuItem from '@material-ui/core/MenuItem'; import MenuList from '@material-ui/core/MenuList'; import * as React from 'react'; export default fu ...

Guaranteeing the Originality of Literal Values within a Record Category

Consider the code snippet below: const VALUES = { field1: "fieldA", field2: "fieldB", } as const export type RecToDU<T> = { [K in keyof T]: T[K] }[keyof T] type VALUESLiterals = RecToDU<typeof VALUES> This re ...

Form a combination of distinct elements from an array of unique types in typescript

I am wondering if it is possible to define an array of unique types based on a union of those types. Let's say I have the following type Value: type Value = string | number Then, I attempted to create a type called Values like this: type Values = ...

Refining dates in the Angular Material Calendar by utilizing two lists obtained from asynchronous sources

I am facing a challenge with disabling certain dates on a Material Calendar. These dates are sourced from two different places. The first set of dates come from within an object (camper) that is provided as input. The second set comes from an API call that ...

Steps to Transform String Array into Prisma Query Select Statement

I have a requirement to dynamically select Prisma columns based on client input: ['id', 'createdAt', 'updatedAt', 'Order.id', 'Order.Item.id', 'Order.Item.desc'] The desired format for selection ...

Document: include checksum in HTML

I have a set of three files. The file named loader.js is responsible for creating an iframe that loads another file called content.html, which in turn loads content.js. I have made loader.js publicly available so that other users can include it on their ow ...

What is the process for obtaining a Component's ElementRef in order to access the BoundingClientRect of that specific Component?

I have successfully created a tooltip using Angular 5.2.0 and ngrx. The tooltip, among other things, receives an ElementRef to the target Element when the state updates, allowing me to position it absolutely: let rect = state.tooltip.target.nativeElement. ...

In TypeScript, encountering an unanticipated intersection

In my "models" registry, whenever I select a model and invoke a method on it, TypeScript anticipates an intersection of parameters across all registered models. To demonstrate this issue concisely, I've created a dummy method called "getName". expor ...

The origin of the Angular img src becomes blurred when invoking a function

I want to dynamically change the image src by calling a function that returns the image path. However, when I attempt to do so using the code below, the image element displays as <img src(unknown)/> component.ts: getMedia(row) { this.sharedData ...