Angular: Why Do Styles Fail to be Applied to Dynamically Inserted HTML Elements?

I am having trouble applying styles to a newly added "i" element as a child element to an HTMLDivElement. The styles set in the scss file are not being applied to the new element.

Is there a way to ensure that the same styles are applied to the newly added "i" element? I want to use the scss/css styles for the new element, rather than setting them through JS(TS) in the .ts file when inserting the element.

This is the code snippet from accommodation-view-data.html:

<div class="star-rating" #starRating>
  <i class="bi bi-star-fill"></i> <!-- Styles are successfully applied to this element -->
</div>

Here are the styles set in accommodation-view-data.component.scss:

i{
  font-size: 1.6rem;
  padding: 0 0.25rem ;
  color: #ffbe0f;
}

And here is the relevant TypeScript code from accommodation-view-data.component.ts:

import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';

@Component({
  selector: 'app-accommodation-view-data',
  templateUrl: './accommodation-view-data.component.html',
  styleUrls: ['./accommodation-view-data.component.scss']
})
export class AccommodationViewDataComponent implements OnInit, AfterViewInit {

  @ViewChild('starRating')
  starRatingElem!: ElementRef;

  constructor() { }

  ngOnInit(): void {
  }

  ngAfterViewInit(): void {
    /* When appending the new element to the DOM,
    * the styles defined in the scss file are not applied to the new element */
    const starIconElement = document.createElement('i');
    starIconElement.classList.add('bi');
    starIconElement.classList.add('bi-star-fill');
    (this.starRatingElem.nativeElement as HTMLDivElement).append(starIconElement);
  }

}

Answer №1

It is common practice for styles integrated in the styleUrls to be component-specific, resulting in each class being reworked for that particular component. This creates a style scope, as highlighted by i[ng-content-lep-c52] in the screenshot below.

Therefore, it is not recommended to add elements directly to the DOM as you have done. It is better to toggle them using ngIf, or use ngFor for items like stars. Otherwise, it will be difficult to make the styling dynamic and bind values to the component model.

In the screenshot, the first element aligns properly with the scoped style, while the new element does not.

NOT RECOMMENDED AND DEPRECATED: To work around this issue, you can utilize the ::ng-deep pseudo class to make a style global, allowing it to override the scoped styles, as demonstrated in a screenshot from this StackBlitz.

For more information on styles in Angular, visit here
https://i.sstatic.net/YasN0.png

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

Exploring and cycling through numerous links using Selenium WebDriver in a node.js environment

Decided to switch from Casper.js to Selenium for access to more tools. Currently trying to loop through multiple links and navigate them using node.js along with selenium-webdriver. Struggling to find any helpful documentation or examples, as I keep enco ...

Using jQuery to access the value of the CSS property "margin-left"

I created a JavaScript game with moving divs that have different transition times. The game includes a function that is called every 1/100 seconds, which checks the position of the divs using: $("class1").css("margin-left") Here's the strange part: ...

Load components dynamically based on list of identifiers

With over 100 components at my disposal, not all of them will be needed on a single page. For instance, a user might select a list of component IDs (components_ids - [7, 50, 22]). When the page is visited, I will only load the components with IDs that ...

position property in div element disrupts slider functionality

I've been working on incorporating a simple slider into my website and stumbled upon this example on jsfiddle My goal is to have the slider positioned "relative" within my site, but when I change the CSS to position: relative;, the slider no longer ...

instructions on incorporating a sidebar into a .NET web page utilizing a master page that lacks a sidebar

I am facing a dilemma regarding adding a sidebar to one specific page of my .net project. The master template does not include a sidebar, so I'm wondering how I can achieve this on just that one page? Here is the code snippet for the Master Template. ...

The dual-file upload feature of the jQuery ajaxForm plugin

After extensive searching online, I have yet to find an answer to my problem. The issue at hand is that when using the ajaxForm malsup plugin, it submits my files twice. HTML: <form id="gallery" enctype="multipart/form-data" action="/upload-gallery.p ...

Issues with formatting of lists

Need help with CSS styling for multiple lists #basic li, #standard li, #premium li { padding-left: 30px; padding-top: 3px; padding-bottom: 5px; background-image: url(../assets/misc/blue_yes.png); background-repeat: no-repeat; background-position: 0 .5em; ...

Is invalid HTML causing issues with Backbone.js templating in Phonegap?

Summary: When my template file contains valid HTML code, it does not display in Phonegap. The structure of my index.html file is as follows: <body onload="onBodyLoad()"> <div data-role="page"> <a href="#login" id="clickme">C ...

How can jQuery verify if the event outcome matches a specific element?

Check out the code snippet below: $('html').on("click", function (e) { if(!$(e).is($element)) { hideResults(); } }); I attempted to use this code, but unfortunately it did not yield the desired outcome. The element in question i ...

Creating a dynamic checkbox feature in Angular using iterations

I'm currently working on a loop that generates checkboxes from a collection. Everything works fine so far, but now I need to set a limit of 8 checkboxes that can be checked (while still displaying all checkboxes). I attempted to use ng-model (and als ...

Learn the process of importing third-party vendor node modules along with their sub dependencies in Angular 2 using angular-cli

Looking to load a more complex node module in an Angular 2 project bootstrapped with angular-cli? The wiki has instructions for loading a single node module, but what about modules with multiple dependencies like angular2-apollo? For example, angular2-apo ...

Using conditional rendering within the map function in React

I am working with the code snippet below and I am looking to implement a conditional rendering to exclude index 0 from being displayed. How can I achieve this? return ( <section> {pokemonCards.map((pokemon, index) => ...

Filling a HTML div with data through PageMethods and AJAX

My issue is quite unique. Despite checking numerous examples before reaching out here, I am facing a peculiar problem. I have a div element in my ASPX file and I am using AJAX to send a POST request to populate it. <script> function send(input ...

TS2604: The JSX element '...' lacks any construct or call signatures and is unable to be processed

As part of our company's initiative to streamline development, I am working on creating a package that includes common components used across all projects. We primarily work with TypeScript, and I have successfully moved the code to a new project that ...

Saving the previous component's DOM in a React application

Understanding the Root.js File const Root = () => ( <HashRouter> <div> <Route exact path="/" component={Main}/> <Route path="/main/:page" component={Main}/> <Route path="/detail ...

Changing an image into a background image

I currently have functional code that retrieves an image inside a div. However, upon checking it on mobile devices, the image appears too small. When I attempt to increase its height, it becomes disproportionate. As a solution, I am attempting to set the i ...

`Is there a way to hide inline text on small screens using Boostrap 4?`

Within this specific scenario, my goal is to conceal the text when viewed on smaller screens and solely display the icon located to the left (an icon representing comments from font awesome): <a id="newCommentLink" href="#"> & ...

Navigate to the correct page when the Button is clicked in a ReactJS/Django project

Embarking on my web development journey, I opted for django/Reactjs to build a social network platform. I created several API methods like account/view_user/ to retrieve a list of users and account/view_user/ for specific user attributes. In React, I cra ...

What is the best way to tally identical values within a Multidimensional Array using Javascript?

How do I find the number of similar values in this 2D array? Need some help! var data = [[0,0],[1,0],[1,0],[1,0],[1,0],...,[7,0]] I am looking for something like this: var data3d = [[0,0,1],[1,0,12],[2,0,25]...... I want to store the count value in the t ...

How to make CSS group checkboxes operate autonomously

I found a checkbox code on Codepen that I really liked, but encountered an issue when trying to use multiple checkboxes at once. Despite customizing it to my preferences, each checkbox only works independently and does not function properly when there are ...