Only one component in Angular is utilizing the scss design

I have a component that generates multiple buttons next to each other, each with a specific style. Additionally, each button is randomly assigned a different color based on its class.

The issue I am facing is that when I include this component in one of my other component HTML files, it displays correctly. However, when I try to add it to another component, the design appears completely off.

It seems like the CSS styles are not being applied to the new components for some reason...

Even though it's the same code as it's an imported component, I'm puzzled by why it doesn't work...

Below is my code:

--> status-bar.component.html

<div *ngFor="let button of [1,2,3,4,5,6,7,8,9,10]; index as i">
    <button id={{i}}  [ngStyle]="getClassrandom(i)"></button>
  </div>

--> status-bar.component.ts

import { Component, Input, OnInit, Output, EventEmitter} from '@angular/core';

@Component({
  selector: 'status-bar',
  templateUrl: './status-bar.component.html',
  styleUrls: ['./status-bar.component.scss']
})


export class StatusBarComponent implements OnInit {


  getClassrandom(i: number): any {
    const classesArray = [
      'status__button status__button--red',
      'status__button status__button--yellow',
      'status__button status__button--green'];
    const element = document.getElementById(i.toString());
    element.className = classesArray[Math.floor(Math.random() * 3)];
  }

  constructor() {
  }
  
    ngOnInit(): void {
    }

  }

---> status-bar.component.scss

.status__button {
    float:left;
    height: 80px;

    width: 25px;
    border-radius: 10px;
    border: 1px solid rgb(255, 255, 255);
    text-align: center;
    -webkit-appearance: none;
    -moz-appearance: none;
    margin: 0;
    box-shadow: 0px 3px 5px 0px rgba(0, 0, 0, 0.2);
    cursor: pointer;
}

.status__button--green {
    background: limegreen;
    box-shadow: 0px 5px 7px 0px rgba(0, 0, 0, 0.2);
    opacity: 0.5;
    &:hover {
        opacity: 1;
    }
}
.status__button--yellow {
    background: yellow;
    box-shadow: 0px 5px 7px 0px rgba(0, 0, 0, 0.2);
    opacity: 0.5;
    &:hover {
        opacity: 1;
    }
}

.status__button--red {
    background: red;
    box-shadow: 0px 5px 7px 0px rgba(0, 0, 0, 0.2);
    opacity: 0.5;
    &:hover {
        opacity: 1;
    }
}

I am using this component in other components like test-bar.component.html or status-bar.component.html

The main component is status.component, which imports all the others along with the status modules.

If anyone has insight into what might be causing this issue, please share your thoughts.

Answer №1

You're combining ngStyle, ngClass, and the className property in your code.

Here's one way to achieve this:

<!--Make sure to use ngClass-->
<div *ngFor="let button of [1,2,3,4,5,6,7,8,9,10]; index as i">
    <button id={{i}}  [ngClass]="getClassrandom()"></button>
</div>

In the getClassrandom() function:

  getClassrandom(): string{
    const classesArray = [
      'status__button status__button--red',
      'status__button status__button--yellow',
      'status__button status__button--green'];
    //Ensure you are returning a string value
    return classesArray[Math.floor(Math.random() * 3)];
  }

Also, instead of passing the index "i" and using document.getElementById which can cause issues if IDs clash, consider using a template reference variable:

<div *ngFor="let button of [1,2,3,4,5,6,7,8,9,10]; index as i">
    <!--Note: This is just an example, avoid [ngStyle] in this context-->
    <button #statusbutton [ngStyle]="getClassrandom(statusbutton)">
    </button>
</div>

getClassrandom(element: HTMLElement): any {
    const classesArray = [
      'status__button status__button--red',
      'status__button status__button--yellow',
      'status__button status__button--green'];
    element.className = classesArray[Math.floor(Math.random() * 3)];
  }

Using a function in a *ngFor loop may not be optimal. You could consider utilizing ViewChildren for better performance:

@ViewChildren('buttonstatus') buttons:QueryList<ElementRef>

ngAfterViewInit()
{
       const classesArray = [
          'status__button status__button--red',
          'status__button status__button--yellow',
          'status__button status__button--green'];
       this.buttons.forEach(x=>x.nativeElement.classNameclassesArray[Math.floor(Math.random() * 3)];=
}

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

Ensure that any relevant information is placed adjacent to a floated image

I am currently designing a responsive webpage featuring images of people's faces placed next to descriptive text. At smaller screen widths, everything looks perfect. However, as the page widens, the text for one person starts next to the image of the ...

Tips for customizing tab pane color using HTML/CSS

I am looking to customize the color scheme of my tab-pane. My goal is to have each tab turn "orange" when clicked, while keeping the rest of the tabs in a "gray" color. Below is the code I am currently experimenting with: <!-- Nav tabs --> <ul ...

The top margin function is ineffective on Internet Explorer 8

<div class="buttons" id="btnHome">HOME</div> <div class="buttons" id="btnCon">CONTACT</div> <div style="clear:both;"></div> <div id="gallery"></div> CSS .buttons{ float:left; padding: 2px 10px 2px ...

Testing the angular unit for a partially functioning ternary condition

Can you help me troubleshoot an issue with my test case for a ternary function? It works fine for true conditions, but not for false ones. I'm not sure what's wrong with my logic. What changes should I make to fix it? public getData(ball: any) ...

What causes the discrepancy between a website's source code and the code viewed in the browser inspection tool? (Regarding web scraping)

This is my first programming project and I apologize in advance for any mistakes in terminology. My Objective: I am currently working on a project to scrape data from my local library's website. My main goal is to automate the process of renewing bo ...

Analyzing HTML content (not properly formatted) using JSoup

When attempting to parse an HTML page using Jsoup, I encountered some unusual issues. The problematic page is located at , and it is not well-formed. This could potentially impact the parsing process. According to Chrome: /html/body/table[2]/tbody/tr/t ...

What is the best way to maintain the order of variadic types for conditionally inferred conditional types?

Here is the type definition that I am working with: type Inner<Type> = Type extends Wrapper<infer U>[] ? U[] : never; Additionally, I have a function with the following signature: function myFunc<From extends Wrapper[], To>( values: ...

How can you retrieve the user that is currently signed in using AngularFire and Firebase Authentication in Angular?

If you're working with Angular and trying to access the currently signed-in user through Firebase Auth, you may encounter some difficulties. Here's a snippet of code provided in the Firebase Auth documentation that demonstrates how to get the sig ...

What is the process of incorporating external links into an angular application?

Attempting to embed an external URL within my Angular app using an iframe has resulted in the following issue: https://i.sstatic.net/liSmX.png The error message reads as follows: https://i.sstatic.net/u9GWw.png Below is the template where I am trying t ...

Exploring the possibilities of combining Angular-CLI and the latest Bootstrap

Embarking on my journey with Angular 2, I decided to use the official angular-cli tool to create a new project. Creating a new project was straightforward: ng new [my-project-name] The project was successfully created and ready for customization. Wanti ...

When selecting an input within a div, the Angular onblur function is behaving erratically

How can I prevent the div from closing when I click on an input inside it after setting a tabindex to the div and closing it on blur? Solution for app.component.html: <button (click)="openToggle('toggle1')">Toggle 1</button> ...

Verify if the web application is in full-screen mode

Currently employing a meta tag to enable full-screen mode for a web app on iPad <meta name="apple-mobile-web-app-capable" content="yes"> Is there a method available to verify whether the app is indeed in full screen? The primary objective is to ad ...

Creating a personalized event using typescript

I need help with properly defining the schema for an EventObject, specifically what should be included within the "extendedProps" key. Currently, my schema looks like this: interface ICustomExtendedProps { privateNote?: string; publicNote?: string; ...

What is the reason for WordPress theme CSS and JS files loading after the head tag?

I'm experiencing an issue where my Wordpress theme's CSS and JS files are loading after the head tag. Additionally, when I view the source in Firefox, they are showing up in red, indicating incorrect markup. Can anyone help me figure out what&ap ...

Responsive Button Sizing with Bootstrap 4

Would it be possible to use Bootstrap 4 to automatically apply the 'btn-sm' class (small button) when the media breakpoint is xs? I want the buttons to remain their default size unless the screen size is xs, where they should switch to btn-sm au ...

Are there any real-world examples you can share of utilizing CSS 3D Transforms?

Can you provide any instances of CSS 3D Transforms being utilized in real-world projects besides and ? ...

npm error - The module './selenium-webdriver/lib/input' cannot be located

After updating my Angular project from version 5 to 7, I encountered numerous vulnerabilities. To address this, I followed the suggested commands in "npm audit" which successfully fixed all the vulnerabilities. However, when attempting to run: ng serve ...

Achieving equal height in Bootstrap columns

Artwork Hey everyone, I'm facing a small dilemma. Currently, I am tackling a project with a unique design. Within the layout of this project, there is an image section that is causing some trouble for me. I am aiming to create a portion of the webs ...

What is the best way to ensure a dropdown menu stays visible while navigating through various If/Else blocks?

I am fairly new to working with PHP and MySQL, so I have been using the mysql_* functions despite knowing that they are no longer supported. However, I can't seem to find anyone else who has had a similar question to mine, which is why I am reaching o ...

What might be causing my website to appear differently on mobile devices?

I am currently using a MacBook with a display size of 15.4 inches (2880 x 1800). Below is a screenshot showing how each section of my homepage appears on my website. QUERY 1 How can I make my h3 text responsive on mobile devices? As shown in the screensh ...