Utilize Property Binding to Access the Map

I am struggling to extract a value from a Map and use it as the background color of a div element, but I can't seem to get it right. My syntax seems off. What mistake am I making?

<div [style.background-color]="bgcolor" width="50px" height="50px"> Hello Green</div>
<div [style.background-color]="bgcolors['a']" width="50px" height="50px"> Hello Red</div>

Within my component, this is what I have:

 bgcolor= "green";
 bgcolors:  Map<string,string>;
 bgcolors = new Map<string,string>();
 bgcolors.set("a", "red");

Check out this jsfiddle link. The first one works while the second one does not.

Answer №1

Check out the solution below. Make sure to use bgcolors.set() properly and access items in Map using bgcolors.get(key).

let { Component, NgModule } = ng.core;

@Component({
  selector: 'my-app',
  template: `
    <div [style.background-color]="bgcolor" width="50px" height="50px"> Hello Green</div>
    <div [style.background-color]="bgcolors.get('a')" width="50px" height="50px"> Hello Red</div>
  `,
})
class HomeComponent {
    bgcolor= "green";
    bgcolors:  Map<string,string>;
    bgcolors = new Map<string,string>();

    name = 'Angular 2';
    constructor() {
        this.bgcolors.set("a", "red");
    }
}

const { BrowserModule } = ng.platformBrowser;

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ HomeComponent ],
  bootstrap:    [ HomeComponent ]
})
class AppModule { }

const { platformBrowserDynamic } = ng.platformBrowserDynamic;
platformBrowserDynamic().bootstrapModule(AppModule);

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

Alert: an issue has been detected in the file located in the directory node_modules/pdfjs

My current project involves incorporating the use of ng2-pdf-viewer, as seen in the code snippet below: {PdfViewerModule} from 'ng2-pdf-viewer/ng2-pdf-viewer'; After upgrading to Angular 6, I have encountered a warning during ng build, even th ...

I'm curious if it's possible to set up both Tailwind CSS and TypeScript in Next.js during the initialization process

When using the command npx create-next-app -e with-tailwindcss my-project, it appears that only Tailwind is configured. npx create-next-app -ts If you use the above command, only TypeScript will be configured. However, running npx create-next-app -e with ...

Having trouble with 'npm <script-command>' not working? Try changing it to 'npm run-script <script-command>' instead

Currently, I am configuring a node js backend to operate on TS for the first time within a mono-repo that has a specific folder structure. You can view the structure here. The package.json file is located in the main directory as shown below: "scr ...

Angular 2's Multi-select dropdown feature allows users to select multiple options

Recently, I encountered an issue with customizing CSS for angular2-multiselect-dropdown. I found the solution in this link: https://www.npmjs.com/package/angular2-multiselect-dropdown. I have included my code below. Any assistance in resolving this matter ...

Terminal displays Typescript variable syntax error

Recently, I've been delving into TypeScript using Visual Studio Code. However, I've encountered a perplexing syntax error that stems from how I've defined a variable. Here's an example of my declaration: let year:number = 2015 My term ...

What could be causing my code to not run after subscribing to the observables?

In my code, I have two methods that return two lists: one for accepted users and the other for favorite users. The first part of my code works well and returns both lists, but in the second part, I need to filter out the accepted users who are also on the ...

Having trouble showing the fa-folders icon in Vuetify?

Utilizing both Vuetify and font-awesome icons has been a successful combination for my project. However, I am facing an issue where the 'fa-folders' icon is not displaying as expected: In the .ts file: import { library } from '@fortawesome/ ...

Angular does not support custom validation as effectively as other frameworks

I am encountering an issue with my Angular form builder where I cannot determine the type of a file after reading it in my custom validation. Here is the link to the code on StackBlitz: https://stackblitz.com/edit/angular-ivy-atwqqc?file=src%2Fapp%2Fapp. ...

Error: Unable to install Angular on WSL due to permission denied for Node

Struggling to set up angular on WSL2, with node version 17.3.1 and npm version 8.3.0 already installed. Received an error when trying the command npm install -g @angular/cli: npm ERR! code 127 npm ERR! path /root/.nvm/versions/node/v17.3.1/lib/node_module ...

Tips for typing a narrow JSX.Element

Is there a way to create a variable in React that can be either a component or a string? Like this: function MyComponent(): JSX.Element { let icon: JSX.Element | string = "/example.png"; return <div>{typeof icon === "JSX.Element" ? icon : <i ...

Using NavParams within a service component,

I'm facing a challenge in accessing NavParams within a provider, and simply importing NavParams is not solving the issue. Here's a brief overview of my application: users input their name and address, a pin is dropped on the map based on the add ...

Tips on deactivating a div when a checkbox is selected

I am currently working with a checkbox element in my code: <md-checkbox checked.bind="addEventCommand.allDay" change.delegate="allday()">All Day</md-checkbox> When the above checkbox is true, I want to disable the following ...

The module '@angular/core' could not be located in the '@angular/platform-browser' and '@angular/platform-browser-dynamic' directories

Attempting to incorporate Angular 2.0.0 with JSMP, SystemJS, and TS Loader in an ASP.NET MVC 5 (non-core) application. Encountering errors in Visual Studio related to locating angular modules. Severity Code Description Project File Line Suppr ...

Angular is experiencing difficulty locating the routing path for the auxiliary `router-outlet`

Exploring the intricacies of routing in Angular to gain a deeper understanding of the concept. Encountering an issue where I am receiving an exception NG04002: Cannot match any routes. URL Segment: 'about' when attempting to click on the About li ...

What steps can I take to ensure that the elements are in the same row instead of being displayed in three separate rows?

(I'm a beginner in web development and need some help) Is there a way to align elements into the same row instead of stacking them up in separate rows? I'm working on creating a header bar similar to the one on the Naive UI Documentation Website. ...

Managing startup errors in Angular 2

Is there a way to capture startup errors such as compilation or dependency injection errors and display a meaningful message instead of just showing 'loading' on a blank page? Using try/catch with bootstrapModule may work in some scenarios: try ...

The SortKey<> function is ineffective, even though the individual types it uses work perfectly fine

After my initial inquiry about TypeScript, the focus shifted to this current topic. In my previous question, I was attempting to develop a generic sort() method that could function with an array of sort keys defined by the SortKey type featured there (and ...

How to utilize *ngFor alongside the async pipe for conditional rendering in Angular 8 HTML

.html <ng-container *ngFor="let contact of listContact | async; let index = index;"> <h6 class="title" *ngIf="contact && contact['type']"> {{contact['type']}} </h6> <div> {{conta ...

The where clause in the Typeorm query builder instance is not functioning properly after its common usage

When fetching data for my relations, I opted to use QueryBuilder. In order to validate certain get request parameters before the index, I established a common QueryBuilder instance as shown below. // Common Get Query const result = await this.reserva ...

SmartEdit functions properly when spartacus is running using yarn start --ssl, but does not work without SSL enabled

I followed the smartedit setup instructions at and everything works well when I start the Spartacus server with yarn start --ssl. However, if I start the server with just yarn start, the storefront does not appear. See image here for reference ...