Adjust the properties within the component's styles using Angular 2

In this project, the objective is to dynamically change the background-color based on different routes. The goal is to display a specific color for UpcomingComponent while keeping the background-color consistent for all other routes.

The approach involves setting the value in STYLES within the /deep/ .classname for background-color dynamically.

Here is the code snippet:

@Component({
  selector: 'app-upcoming',
  templateUrl: './upcoming.component.html',
  // styleUrls: ['./upcoming.component.css'],

  styles: [`
  /deep/ .root {
    background-color: color;
  }`]
})

export class UpcomingComponent implements OnInit {

  color: string;

  ngOnInit() {
    this.updateBackgroundColor();
  }

  updateBackgroundColor() {
    if (window.location.pathname === '/upcoming'){
      console.log("Color updated");
      this.color =  'purple';
    }
  }

}

Answer №1

It is not recommended to bind in styles or styleUrls. Instead, consider using [class.xxx]="...", [ngClass]="...", [style.xxx]="...", [ngStyle]="..." bindings on the specific element you wish to style.

Answer №2

I successfully implemented the Route function in my AppComponent. Huge thanks to @Günter Zöchbauer for providing invaluable assistance.

import { Component } from '@angular/core';
import {Router , ActivatedRoute,NavigationEnd} from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']

})
export class AppComponent {


  constructor(private router:Router,private activatedRoute:ActivatedRoute) {

    router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
         if (event.url === '/upcoming') {
          document.body.style.background = 'grey';
      }else {
          document.body.style.background  = 'blue';
      }
      }
    });
  }
}

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

How to effectively manage multiple stylesheet links in React Native Expo development

Hello, my name is Antika. I recently embarked on a coding journey and have been focusing on learning HTML/CSS/JS along with the basics of React. As a beginner developer, my current project involves creating a Study planner app for myself using React Native ...

React/Javascript - Executing Function returns prematurely

I have been working on a function that takes an object and iterates through it to create a search query. However, the issue I'm facing is that the function returns before I finish looping through the object: export default function buildQuery(query) ...

The functionality of the Vue.js single file component is not performing as anticipated

Recently, I've been experimenting with Vue and Vue CLI. I came across this amazing vue-tabs-component that I would like to try out. Here is a snippet of my code from App.vue: <template> <div> <tabs> <tab name="Fir ...

What is the best way to organize a redux state to meet these specific needs?

In managing a complex web application state, it is crucial to keep track of multiple elements such as selected items and display IDs. The application may house several instances of these "States" with only one being active at any given time. For instance, ...

A step-by-step guide on customizing the background color of a Dialog in Angular Material (Version 16)

I've been attempting to modify the background color of my Angular Material Dialog by utilizing the panelClass property in the MatDialogConfig. Unfortunately, I'm encountering a partial success. I am aiming to set the background color as red (jus ...

How can I generate a list of JavaScript files to be included in a template for both production and development environments using Grunt?

I need a way to organize a list of JavaScript files in one central location, either within gruntfile.js or an external JSON file, and then dynamically implement it into a template for both development and production environments. List of JavaScript files: ...

Is there a way to retrieve the original JSON string from a GWT JavaScriptObject?

Working with JSONP in my GWT application has presented some challenges. When the server sends a json string, I am able to retrieve it in the form of a JavaScriptObject on the client side. The issue arises when my json data contains complex structures, usi ...

What is the best way to write an SQL query to safely insert a record into a table with a dynamic name?

I'm working on a function that can insert a record into a table in PostgreSQL. The catch is that the table name needs to be a parameter for the function, and the column names are determined dynamically. To ensure protection against SQL Injection, I am ...

Tips for replacing default arrow icons with 'Previous' and 'Next' buttons in a Material-UI pagination element

I've been struggling to find a solution with my code provided below. Despite multiple attempts, the issue remains unresolved. import React from "react"; import { gridPageCountSelector, gridPageSelector, gridPageSizeSelector, useGridA ...

[Vue alert]: Component mounting failed due to usage of mixin with a parameter

For the past day, I've been facing difficulties creating a Vue mixin with a parameter. When attempting to do so, I encounter a [Vue warn]: Failed to mount component: template or render function not defined error. Below is my JS file which includes the ...

What is the best way to distinguish the Footer from the Content?

While I was honing my skills in crafting a website using only HTML and CSS, I encountered an issue. I couldn't figure out how to place the footer beneath the content properly. My goal was to clearly separate each section - header, content, and footer. ...

Scouring the web with Cheerio to extract various information from Twitter

Just starting out with Web Scraping, using Axios to fetch the URL and Cheerio to access the data. Trying to scrape my Twitter account for the number of followers by inspecting the element holding that info, but not getting any results. Attempting to exec ...

Vue 2.0 custom filter not producing any output

I am attempting to create a customized filter that identifies and returns the items that correspond to a given input. It functions effectively with basic arrays like ['Apple', 'Banana', 'Cupple'], but encounters difficulty whe ...

Error: Unable to access the property of an undefined variable in Angular 4

Here is what I currently have in my code: <p *ngIf="model.something.satisfy"> Yes </p> <p *ngIf="!model.something.satisfy"> {{model.something.comments}} </p> The issue arises in the second line with the error message "Type ...

Store data in LocalStorage according to the selected value in the dropdown menu

Can you help me understand how to update the value of a localstorage item based on the selection made in a dropdown menu? <select id="theme" onchange=""> <option value="simple">Simple</option> <option valu ...

Is there an equivalent of getElementById for placeholder text?

I need help automating the input of information on a webpage using JavaScript. Each field has a unique ID, like this: <div id="cc-container" class="field has-float-label"> <input placeholder="ccnumber" id="credit_card_number" maxlength="16" ...

How can I add color to arrow icons in tabulator group rows?

Is there a way to specify the color of the arrows in collapsed/expanded group rows? Also, what CSS code should I use to define the font color for column group summaries? You can view an example of what I am trying to customize here: https://jsfiddle.net/s ...

Transitioning the font stack from SCSS to JSS (cssinjs)

We are currently implementing a variety of custom fonts with different weights for various purposes. With our entire stack now using Material UI with JSS theming and styling, we aim to eliminate the remaining .scss files in our folder structure. All the f ...

Resetting a JQuery button to its initial state

I have a button that, when clicked, rotates to 25deg thanks to Jquery. Now, I want it so that if I click the button again, it returns to its original position. Here is what I have tried: $(document).ready(function() { $(function() { ...

Include a lower border on the webview that's being shown

Currently, the webview I'm working with has horizontal scrolling similar to a book layout for displaying HTML content. To achieve this effect, I am utilizing the scroll function. My inquiry revolves around implementing a bottom border on each page usi ...