Angular: What is the best way to retrieve the class name in the app-root from a local component?

My website consists of three main pages and multiple child pages. Each child page inherits its style from the parent CSS.

country.routes.ts

 ...
 path: '',
 children: [
    { 
      path: '/country', 
      component: CountryComponent, 
      data: {
        cssClass: 'country',
      },
    },
    { 
      path: ':countryId/city', 
      component: CityComponent ,
      data: {
        cssClass: 'country-city',
      },
    },
    {
      path: ':countryId/fact', 
      component: FactComponent,
      data: {
        cssClass: 'country-fact',
      },
    },
...

The CSS class is added to a div just below the app-root, as shown below:

index.html (just rough html representation)

<app-root>
 <div clas="country/country-fact/country-city">
  <header></header>
  <div>
   <route-outlet>
    <main>
     <!-- content -->
    </main>
   </route-outlet>
  </div>
  <footer></footer>
 </div>
</app-root>

In the main.scss (global styles)

country {
  background-color:red;
}
country-city {
  background-color:blue;
}
.country-fact {
  background-color: purple;
}

Since this website is built using Angular, I utilized view encapsulation by declaring the styles in the component decorator:

country.component.ts

@component({

 ...
 styles: ['
  :host-context(.country) main{
    background-color:red;
 ','
   :host-context(.country) header{
     display:none;
    }
 '],

country-city.component.ts

@component({

 ...
 styles: ['
  :host-context(.country-city) main{
    background-color:blue;
 '],

country-fact.component.ts

@component({

 ...
 styles: ['
  :host-context(.country) main{
    background-color:purple;
 '],

Based on my reading and tutorials:

I came across a tutorial that explained how to modify the parent's CSS using ':host' or ':host-context(.selector) .change-selector'. However, it did not mention the possibility of using these selectors at the body or app-root level.

I experimented with nested `

:host` or `:host{ :host-context()}, but both attempts failed.</p>

<p>Another <a href="https://blog.angular-university.io/angular-host-context/" rel="nofollow noreferrer">article</a> mentioned selecting at the body level using the pseudo-class, but I could not get it to work. While researching, I found information suggesting that <code>:host-context
functions similarly to :host but with a selector, limiting it to selecting only the parent's class and not extending to the body level.

Answer №1

The issue stems from the fact that the main element is not within the scope of the component where you are applying the styles.

After reviewing the official documentation on host-context (https://angular.io/guide/component-styles#host-context), it is clear that CSS styles can only be applied to elements WITHIN the component, based on external conditions.

In order to apply a background-color style to all internal elements inside a component, you can use the following example:

:host-context(.theme-light) h2 {
  background-color: #eef;
}

To achieve your desired outcome, you will need to include these styles within the component containing the main tag, place the main tag within your country components, or adjust the targeting rules to focus on an element within the country components (rather than the main tag).

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

Guide on loading a PDF asset dynamically within an Angular application with the help of webpack

I am having trouble loading a PDF file into my Angular app, which is running on the webpack dev server. I am using the HTML <object> tag with the data attribute to achieve this. The issue arises because the PDF path is generated dynamically at runti ...

How to extract information for divs with specific attribute values using Jquery

I have multiple divs with IDs like #result-1, #result-2, each followed by a prefix number. To count the number of list items within these divs, I use the following code: $(document).ready(function () { var colorCount = $('#result-1 .item-result ...

Exploring the issue of varying site header widths in WordPress: The mystery behind my unfinished author page

Why is there a difference in site header width between the author page and other pages? It seems incomplete on the author page while it's complete on other pages. What am I missing? <header id="site-header" role="banner&q ...

Use `$$state: {…}` within the request rather than the data

When attempting to send a request with data, I am only getting "f {$$state: {…}}" in the console. $scope.createTask = function () { var req = $http.post('api/insert', { title: $scope.newTitle, description: ...

What is the best way to establish and concentrate on a fresh component in AngularJS?

I am working on a form that has a dynamic number of inputs, which is controlled by AngularJS. <body ng-app="mainApp" ng-controller="CreatePollController" ng-init="init(3)"> <form id="createPollForm"> <input class="create-input" ...

Is there a way to dynamically add <td> based on the quantity of values in a JSON object?

I have developed a program that retrieves values from JSON and I aim to display these values in a table. Currently, only the last array value is being displayed in the table even though all values are available in the console. The objective now is to dynam ...

Position the div so that it is aligned with the top offset of another element

My question is straightforward. I have a div1 element with a variable offset().top that adjusts based on other elements on the page. I am looking to add an absolutely positioned div next to it, which should have the same absolute top value. This can be ach ...

The JQuery function .html() fails to include all the HTML content retrieved from a JSON response

I've created some HTML using PHP's json_encode(), and it looks like this: ob_start(); if ($my_query->have_posts()) : while ($my_query->have_posts()) : $my_query->the_post(); get_template_part( 'template-par ...

The object's null status remains uncertain even after being checked for null

Currently, I am working with Typescript 2.8 This is the code snippet that I have: class Wizard extends React.Componenet { private divElement: null | HTMLDivElement = null; componentDidUpdate(_: IWizardProps, prevState: IWizardState) { i ...

What is the best way to format MySQL table data into rows and columns for display?

<?php mysql_connect('server', 'user', 'Pass'); mysql_select_db('add'); $query =mysql_query('select * from addimage'); while( $row = mysql_fetch_assoc($query) ) { echo "$row[url]"; } ?> This code ...

Style binding for background image can utilize computed properties or data for dynamic rendering

In my code, I am trying to pass an object that contains a string path for its background image. I have experimented with using data and computed properties, but so far I haven't had any luck getting them to work within the :style binding. However, if ...

displaying the information when we mouse over a specific row in the table

I need to display a pop-up with data from a table row, similar to the image at this URL for CS WHOLESALE GROCERS. I've implemented the following AngularJS code in my controller: app.directive('tooltip', function(){ return { res ...

Using Selenium to Implement Accept Policy Targeting

I am attempting to locate and click on a button from dekudeals using selenium. Specifically, I am trying to target the accept button within the site's policy window. The button that needs to be clicked can be found here. I have made several attempt ...

Trying to open the DB URL in a new tab when using PHP and MySQL will not work as expected

Before I begin, I want to express my gratitude to the community of StackOverFlow users for providing valuable answers. As a novice in PHP/mySql, I am learning through books and examples from others. Currently, my issue revolves around a MySQL database wit ...

A proposal for implementing constructor parameter properties in ECMAScript

TypeScript provides a convenient syntax for constructor parameter properties, allowing you to write code like this: constructor(a, public b, private _c) {} This is essentially shorthand for the following code: constructor(a, b, _c) { this.b = b; thi ...

Using HTML's select option to submit a request for data retrieval from PHP using PDO with MySql database

I am having an issue with fetching data from MySQL based on Select Month and Year in HTML Select Option. When I submit the view, the table should be filtered accordingly. Otherwise, all data should be displayed. However, my code is generating an error. No ...

What is the best way to correctly redirect users to different pages based on their user group in Django?

I have implemented a new feature where banned users, those without any group affiliation, are directed to a specific page banned_alert when they try to post content. However, upon testing this feature, Chrome displays an error message saying "This page isn ...

The issue with ui-router failing to render the template in MVC5

I'm having trouble setting up a basic Angular UI-Router configuration. My goal right now is to have a hardcoded template render properly, and then work on loading an external .html file. My project is using MVC5, so I'll provide the necessary fi ...

Tips for displaying a gallery of 5 images in a 2-row slider using bxslider

I've been attempting to create a unique image slider using bxslider. My goal is to have a 2-row slider with 5 images displayed in each row. However, I'm encountering difficulties when I try to integrate the HTML, CSS, and JavaScript code. Despit ...

Additional white sheet included with TCPDF

I have been working with TCPDF to convert PHP-generated pages from MySQL queries. Each record is contained within a div and uses the style "page-break-after:always". However, I am encountering an issue where an extra blank page appears at the end of the PD ...