Styling with CSS in Angular 2+ can be quite challenging

Hey there, I'm new to Angular 4 and running into some troubles with styling my application. I tried adding a background image to the body, which worked fine, and then added a component to display content, also looking good.

Now, when I added a second component with a different route, I didn't want the body to have the same background image. I've been reading up on best practices and came across the idea of having a separate style for the body at the component level by using a body style override in styleUrls. However, every time I switched from one route to another, the background stayed the same instead of changing based on the component. Could this be due to my use of ViewEncapsulation set to None?

In addition, here is how my setup looks:

index.html:

<head>
 <body>
   <app-root></app-root>
  </body>
</html>

app.component.html:

<app-navigation></app-navigation>
<router-outlet></router-outlet>
<app-footer></app-footer>

Welcome.component.html:

<section id="hero">
  <div>
  </div>
</section>

The welcome component displays the background correctly, but as soon as I navigate to another component using something like "this.router.navigate(['/page2']);", the background remains the same. If I refresh on /page2, the correct background appears.

UPDATE: I decided to give up on showcasing a background image for the second component, while still maintaining it for the first one. After removing ViewEncapsulation from all components, moving the body {} to the first component resulted in the background not showing up (even though the path was correct). Is there a better solution than resorting to DOM manipulation? What would be considered the best practice in this scenario?

Answer №1

Make sure to add a custom style class during the ngOnInit lifecycle hook and remove it when ngOnDestroy is called.

constructor(private handler: Handler) {
   }

ngOnInit() {
    this.handler.addStyle(document.div, 'new_style');
  }

ngOnDestroy() {
    this.handler.removeStyle(document.div, 'new_style');
  }

Answer №2

This solution worked wonders for me, give it a try! Start by implementing the following changes in your component1:

ngOnInit() {
    document.body.style.background="url(https://encrypted-tbn0.gstatic.com/lcr7rxzoa/images?q=tbn:ANd9GcSu5rIAFQkkswZLuwAUCXZqc_8bBROGkGgmZP5bmGk57sRKXWJMEg)";
}

ngOnDestroy() {
  document.body.style.background="";
}

Now, move on to your component2 and make these adjustments:

ngOnInit() {
    document.body.style.background="url(http://gkreading.com/wp-content/uploads/2017/03/awesome-kid-in-the-grass.jpg)";
}
ngOnDestroy() {
      document.body.style.background="";
}

Hopefully this solution works well for you too!

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

What are some methods for toggling text visibility in PHP?

I am facing confusion regarding the functionality of this code. Here is the snippet in question : //start date to end date <?php if($show5 < $show6) { ?> <a>show content</a> <?php }?> If both 'start da ...

What could be the reason for my npm package installed globally to not be able to utilize ts-node?

Recently, I've been working on developing a CLI tool for my personal use. This tool essentially parses the standard output generated by hcitool, which provides information about nearby bluetooth devices. If you're interested in checking out the ...

How can I eliminate the black outline added to text by IE CSS filter?

Is there a way to add text-shadows to elements in IE without having a black outline around the text when it is not black? I know IE doesn't support text-shadow property but using filter: property gets pretty close. If anyone has any suggestions or so ...

An easy way to enable mobility for BootstrapDialog on mobile devices

Currently, I am utilizing the library available at https://github.com/nakupanda/bootstrap3-dialog in order to create a dialog box. However, my issue arises when viewing the dialog on mobile devices where it exceeds the screen size. On desktops, adjusting t ...

What is the best way to identify errors in an express listen callback function?

My current code is set up to verify if there was an error while initiating Express: express() .listen(port, (err: Error) => { if (err) { console.error(err); return; } console.log(`Express started`); ...

URL for CSS Background-Image

While working on CSS styling for the body, I ran into a problem and was curious to understand the distinction. Initially, I tried this body { background-image: url('img/bg.png'); } However, it did not produce the desired result. http://www ...

What is the best way to confirm that a certain element is not present on the page using playwright?

My current challenge involves testing a website that features a logo, and I need to ensure that the logo does not display on specific pages. I have been exploring the Playwright assertions documentation for guidance on how to assert that an element does N ...

Web application experiences freezing issues when utilizing specific components in certain situations

Currently, I am in the process of developing a web application using Angular. In this project, there is a parent component and multiple child components that receive data from an rxjs Subject. One of the child components is being used in another section o ...

Is the image inside a responsive div?

I'm currently working on my first website that I am proud of, and I am in the process of creating a background using CSS and an image. I want it to look exactly like the picture. . I have successfully achieved this (accomplished already), but the is ...

Tips for storing the device token received from Firebase Cloud Messaging in an Ionic2 application

Using the FCM plugin for ionic2, I was able to successfully implement push notifications. For reference, you can check out the plugin here. I followed the steps outlined in this Github repository, and everything is working smoothly so far. Now, my next go ...

The interconnectivity between ngAfterViewInit in Angular's LifeCycle and observables

enable.service.ts @Injectable({ providedIn: 'root' }) export class EnableService { isEnabled$ = from(this.client.init()).pipe( switchMap(() => this.client.getEnabled()), map(([enabled, isAdmin]) => ({enabled: true, isAdmin: fals ...

Optimal approach to configuring Spring Boot and Angular for seamless communication with Facebook Marketing API

Currently, I am working on a Spring Boot backend application and incorporating the Facebook marketing SDK. For the frontend, I am utilizing Angular 10. Whenever I create a new page or campaign, my goal is to send the corresponding object back to the fronte ...

The code for filtering an array in Angular 9 seems to be failing to display the expected filtered items

Here is the JSON data: [ { "products": [ { "id": "1", "name": "Apple", "price": "free", "category": "Fruits" }, { And so on And this : [{ "categories": [ ...

Issues with Laravel 5.8 and Bootstrap not functioning properly in Jquery

Check out this link for using Bootstrap Select. The code works perfectly in the view, but when I try to implement it with jQuery below, it doesn't work. Can someone help me fix this issue? View Code: <table id="tableAppointment" style=&q ...

What is the best way to reposition an element to the end of its flexbox container?

I have a flexbox-container that contains multiple details-elements with flex-wrap behavior. My goal is to have a details-element move below the other elements within the container when it is opened. For example, I want it to go from this initial layout: ...

Ensuring the modal is stored in one central location (Bootstrap)

I'm currently working on a website project using bootstrap, and I need to incorporate the same modal across all pages. Right now, I find myself duplicating the entire code in each HTML file to make it accessible on every page. However, this method is ...

Typescript not flagging an error for an object being declared without a type

I am encountering an issue with my tsconfig.json file: { "compilerOptions": { "allowJs": true, "allowSyntheticDefaultImports": true, "baseUrl": "src", "isolatedModules": true, "jsx": "preserve", "esModuleInterop": true, "forc ...

Transform the appearance of Angular Material's table with a new design

Currently, I am working with Data-Table from angular material and I am looking to customize the table style to better suit my needs. https://i.sstatic.net/KyJm8.png I'm wondering how I can remove the border/frame from the table and eliminate the 3D ...

Trouble with maps not showing up and the console isn't showing any errors when using @react-google-m

Currently, I am facing an issue while trying to integrate Google Maps by following a blog post that provides instructions on next13 TypeScript. Despite reaching the point where the maps should be displayed, nothing appears on the screen. Surprisingly, ther ...

The data retrieved from the web API is not undergoing the necessary conversion process

I am facing an issue with a web API call where the property checkNumber is defined as a double on the API side, but I need it to be treated as a string in my TypeScript model. Despite having the property defined as a string in my model, it is being receive ...