Guide to Using Array Values as Colors in Angular 4

Hello fellow Angular and Stack Overflow users! I'm still getting the hang of Angular 4 and need some guidance. Can someone tell me if it's possible to pass an array value in the element binding in Angular 4?

My goal is to dynamically change the color of the #jediSign based on whether or not a student is a Jedi!

Here's the template code:

<div *ngIf="student">
  Student: <a href="#" (click)="clicked()">{{student?.name}}</a>
  <br/>
  <div *ngIf="student?.isJedi">
  Jedi Temple: {{student?.temple}} <br/>
  </div>
  <div #jediSign class="jediSign"></div>
  <button (click)="jediSign.style.background='lightgreen'">Is Jedi?
  </button>
 </div>

And here's the component code:

export class AppComponent {

 students: Student[] = [
  {
   name: 'Luke', 
   isJedi: true, 
   temple: 'Coruscant', 
   color: 'lightgreen'
   },
  {
   name: 'Leia', 
   isJedi: false, 
   color: 'red'
   },
  {
   name: 'Han Solo', 
   isJedi: false, 
   color: 'red'
  }
 ]
}

Any ideas on how I can change the color from 'lightgreen' to students.color?

I've uploaded this code on GitHub for pull requests. Your help is greatly appreciated!

Thank you in advance!

Answer №1

Simply adjust the color using ngStyle:

<div ... [ngStyle]="{'background-color': student.isJedi ?
 student.color : 'lightgrey'}"..>

and

  <button (click)="student.isJedi = !student.isJedi">...

Answer №2

To achieve the desired result, it is recommended to utilize the style.background attribute like so:

<div *ngIf="student">
  Student: <a href="#" (click)="clicked()">{{student?.name}}</a>
  <br/>
  <div *ngIf="student?.isJedi">
  Jedi Temple: {{student?.temple}} <br/>
  </div>
  <div #jediSign class="jediSign" [style.background]="isJediBackgroundColor(student)" ></div>
  <button (click)="student.isJedi = !student.isJedi">Is Jedi?
  </button>
 </div>

It's necessary to create a function that determines the background color based on the value of isJedi:

isJediBackgroundColor(student) {
  return student.isJedi ? student.color : '';
}

Additionally, ensure that the click event functions correctly to toggle the status of isJedi:

(click)="student.isJedi = !student.isJedi"

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

Easily retrieve the value of a form control when it is changed with Form

Currently, I am in the process of reviewing Formly. In my initial attempt, I am trying to trigger a method when the content of a textarea changes. The code snippet below shows what I have tried so far. Unfortunately, it seems like the functionality is no ...

AngularJS Currency Converter - Converting Currencies with Ease

I have a question regarding the most efficient way to handle currency conversion on a webpage. Currently, I have multiple input fields displaying different currencies. When a user clicks on the currency conversion button, a modal popup appears. After the ...

Tips for building a versatile client-server application with separate codebases for the JavaScript components

We are embarking on the process of rebuilding our CMS and leveraging our expertise with VueJS. Despite our familiarity with VueJS, we won't be able to create a full single-page application due to the presence of server-side rendering files (JSP). The ...

Sharing slices of data among feature modules in NgRx allows for improved scalability and organization

I'm a newcomer to the world of NgRx and I find myself with some inquiries regarding the proper way to organize the state within a Store. Currently, we are in the process of developing an internal CRM system using Angular to manage client information. ...

How can I delete the black background from the ion-tab-bar in Ionic 7?

In my current project using Ionic 7, I have a navigation guide set up with 4 tabs. I am trying to customize the styling of these ion tabs by adding some custom CSS. The issue I'm facing is that despite my attempts to make the background transparent, ...

Removing a targeted element from an array in Angular

After receiving a JSON array object in Angular using TypeScript, I am attempting to remove a specified object from it. However, my attempts at deletion have been unsuccessful. addCategorySub(categorySub: CategorySubModel, index: number) { categorySub.id ...

Struggling to retrieve the 'this' object using a dynamic string

Within my Nuxt + TS App, I have a method that attempts to call a function: nextPage(paginationName: string): void { this[`${paginationName}Data`].pagination .nextPage() .then((newPage: number) => { this.getData(pagination ...

Backdrop styling for Material-UI dialogs/modals

Is there a way to customize the semi-transparent overlay of a material-ui dialog or modal? I am currently using material-ui with React and Typescript. https://i.stack.imgur.com/ODQvN.png Instead of a dark transparent overlay, I would like it to be transp ...

How can I use Angular 7 to create a background image for a View made up of multiple components?

Here is the HTML code that I am working with: <app-navbar></app-navbar> <router-outlet></router-outlet> My goal is to have an image set as the background for the home view, which consists of two components: navbarComponent and hom ...

Issue with data updating in Angular rxjs with share, map, and filter functions

After gathering search criteria from a form, I have developed a method that retrieves an observable of talents. fetchTalents(searchCriteria) { return this._allUsers$.pipe( tap((talents) => console.log(talents)), map((tale ...

Utilizing the spread operator in Typescript to combine multiple Maps into a fresh Map leads to an instance of a clear Object

Check out the code below: let m1 = new Map<string, PolicyDocument>([ [ "key1", new PolicyDocument({ statements: [ new PolicyStatement({ actions: [&q ...

What is the role of the handleSubmit parameter in React Hook Form?

I'm encountering an issue with TypeScript in the handleSubmit function. To start off, I am accessing the handleSubmit function through the useForm hook: const {handleSubmit, control, watch, reset} = useForm() Next, I define a submit function: con ...

Validating forms using TypeScript in a Vue.js application with the Vuetify

Currently, I am attempting to utilize Vue.js in conjunction with TypeScript. My goal is to create a basic form with some validation but I keep encountering errors within Visual Studio Code. The initial errors stem from my validate function: validate(): v ...

Angular Kendo UI File Uploader

I faced a challenge with the Kendo Ui Angular's kendo-upload component. I needed to provide [saveUrl] and [removeUrl] in the kendo-upload, but since I split the project into service and component parts, I opted to handle the Upload logic myself within ...

What is the best way to address an unsatisfied peer dependency?

I have come across a new library, ngx-translate, that I am interested in utilizing for my application. When attempting to install it, I encounter the following issue: npm install @ngx-translate/core --save Upon installation, I receive notifications abou ...

Angular 6: Prevented Loading Resource Due to Content Security Policy: A script from self was blocked from being loaded on the page

Currently, I am developing a project in Angular 6 and everything seems to be running smoothly. Running the command ng --serve and building it using ng build results in no errors when deploying it on my local Tomcat Server. However, when attemptin ...

Guidance on transferring information from a parent component to an Angular Material table child component

Currently, I am implementing an angular material table with sorting functionality. You can view the example here: Table Sorting Example I intend to transform this into a reusable component so that in the parent component, all I have to do is pass the colu ...

When the parent component is linked to the child, the screen remains empty

Attempting to pass a variable from the parent component to the child component led me to utilize the @Input() method. However, when I tried to establish the connection between the two components, the entire website displayed a blank page and became unrespo ...

Error: Angular Material module could not be located even after importing additional modules

Encountering an error in angular when trying to import a new material module: ERROR in ./src/app/app.component.ngfactory.js Module not found: Error: Can't resolve '@angular/material/core/index' in 'C:\Users\hrshcse\angul ...

Adding an attribute to the last item of an Angular / NGX Bootstrap component

I am working with a dynamic list that utilizes NGX Bootstrap Dropdowns to showcase 4 sets of dropdown lists. However, the Dropdowns in the final list are getting obscured off-page. Thankfully, NGX Bootstrap offers a solution in the form of a dropUp option ...