Angular encounters issue when retrieving CSS file while navigating to a nested route

When trying to access a child component directly in production mode (using ng serve --prod), it fails to load the CSS file as it attempts to fetch it from a nested path. For example, when navigating to "localhost:4200/doc/", the CSS Request URL is:

localhost:4200/doc/styles.6eab038f040a1c7c7ed6.css.

An error message is displayed:

Refused to apply style from 'http://localhost:4200/doc/styles.6eab038f040a1c7c7ed6.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

However, when accessing the root (localhost:4200), the CSS loads correctly. The issue only arises when directly navigating to a child component while in production mode, and does not occur on the development server. No changes have been made to the default settings regarding styles.css.

          "styles": [
          "src/styles.css"
        ],

Any ideas on what could be causing this problem?

Edit

I discovered that the issue occurs specifically when navigating to nested routes (thanks to the reply from mikegross).

The problem does not occur on routes without nested parameters, but on routes with nested parameters (such as 'doc/:id'), it does.

Router module:

const routes: Routes = [
  { path: '', redirectTo: 'list', pathMatch: "full"},
  { path: 'list', component: ListComponent},
  { path: 'doc/:id', component: DocumentComponent},
  { path: '**', redirectTo: ''},
];

@NgModule({ 
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Update (Feb. 28)

Since my project was still relatively small, I created a new Angular project, installed the same dependencies, and copied the code over. Surprisingly, in the new project, the problem did not occur. The only noticeable difference was a minor version update (ng 9.0 to 9.1).

Answer №1

While this post may be older, I found a workaround by utilizing query parameters instead of route parameters. For example:

const routes: Routes = [
  { path: '', redirectTo: 'list', pathMatch: "full"},
  { path: 'list', component: ListComponent},
  { path: 'doc', component: DocumentComponent},
  { path: '**', redirectTo: ''},
];

(I eliminated the :id from "doc/:id")

To navigate to the route:

this._router.navigate(['/doc'],{queryParams: {id: id}});

Then you can retrieve the query parameter like so:

this._activatedRoute.snapshot.queryParamMap.get('id');

Answer №2

Joined the party a bit late, but I encountered a similar issue with React in 2022.

Initially, I linked the CSS file using a relative path like this:

<link rel="preload" href="./style/Avenir-Light.woff2" as="font" type="font/woff2" crossorigin>

However, once I switched to using an absolute path, everything started working smoothly.

<link rel="preload" href="/style/Avenir-Light.woff2" as="font" type="font/woff2" crossorigin>

Hopefully, this tip will benefit others who come across the same issue in the future.

Answer №3

Dealing with a similar problem, I found the solution by updating the base-href value in the angular.json file instead of the index.html file.

In the angular.json file, I made the following modification:

baseHref: "/"

After making this change, the issue was successfully resolved.

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

Rotation of the SVG coordinate system distorts angles

My comprehension of SVG, particularly the viewport, viewBox, and the user coordinate system, seemed fairly solid. In the initial example provided below, we utilized a viewBox with a matching aspect ratio as the viewport. As expected, there was no distorti ...

Hide the first div within the inner div of a section using CSS

I am working on a section that contains multiple nested divs. Within each outer div, there are 3-4 inner divs. My goal is to hide only the first inner div of each outer div while still displaying some text. section div div:nth-child(1){ display: n ...

Retrieving user data from Ngrx store upon page refresh

Is it safe to retrieve user data from the database and store it after refreshing the page? Currently, I am getting the user ID from local storage in Guard and dispatching an action to retrieve the user data. Should I consider a different approach for thi ...

Why isn't the background image showing up on iOS devices when using the slider?

The website's background image displays on all devices such as laptops and Android phones, but not on iOS mobile devices. I even resized the image to 768px * 365px, but it still doesn't work. .bg-img { position: absolute; left: 0; ...

Issue arises when the value becomes nonexistent following the execution of a

Having an issue with my code where I have one class with a function in it, and another class that imports the first class to use that function. However, after the function is executed, I am not getting the expected value. First class: export class MoveE ...

Use one tag to abbreviate multiple times

As I create a step-by-step guide, I want the audience to be able to hover over any word in the text and see its definition. However, I only want to define abbreviations once. Is there a method in html or css that allows me to achieve this? ...

Where could one possibly find the destination of the mysterious <circle>?

I want to implement a simple pulsating animation on a circle svg element. I attempted using a transform: scale(..,..) animation, but it seems to be shifting the entire circle within its container instead of just scaling the element itself. This is the cur ...

Hovering over one element in Jquery triggers actions on multiple elements simultaneously

I'm working on a project where I have multiple cards, and I've implemented a hover effect using jQuery to make the images inside the cards bigger. However, I'm facing an issue where hovering over one card triggers the effect on all the other ...

A guide on how to use Bootstrap to align elements at the center of a div container

My attempt to center an image in the div didn't quite work out as planned. Here's the snippet of my html and css: .col-xs-4 { background-color: lightgrey; width: 300px; height: 200px; border: 6px solid green; padding: 25px; margin: ...

Enhance Your File Uploads with Custom Images in Bootstrap

For the file upload buttons, I have used the given image by customizing the button look using Bootstrap 3. Here is an example of how I achieved this: <label class="btn btn-primary" for="my-file-selector"> <input id="my-file-selector" type="fi ...

Tips for retrieving a JSON object value using a key in Angular 6 View

As a beginner in Angular 6, I am struggling to figure out how to access values from a JSON object in the view using keys. In my service, I am making an http.get(url) call and then invoking that method in my component. export class CustomersComponent impl ...

Internet Explorer is throwing unexpected routing errors in Angular 2

I have a spring-boot/angular 2 application that is working perfectly fine on Chrome, Safari, Opera, and Edge. However, when accessed through Internet Explorer, the app directly routes to the PageNotFound component. I have tried adding shims for IE in the i ...

What is the reason for needing a unique input name when sharing components?

After struggling to determine why my code was unable to retrieve the number of items in the featured items section, I finally discovered that changing the variable from "input" to "search" resolved the issue. Below is a snippet from my featured-item.compon ...

In HTML, a Bootstrap row appears on top of another row when viewing on mobile devices

I have implemented a Bootstrap HTML section that consists of a container and two main rows. Here is the code snippet: <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <style& ...

Incorporating user input into a div element

So, I'm in the process of building my own Task Tracker using JavaScript to enhance my skills, but I've hit a roadblock. I successfully implemented adding a new div with user-inputted tasks, however, there's no styling involved. <div cla ...

A clever approach to toggling the visibility of elements in Angular2 using complex conditions

My webpage includes 10-12 buttons and a few other input fields. Depending on user roles and types, I need to control the visibility of these buttons and inputs. For instance: If user type = a, then hide 3 buttons and 2 inputs. If user type = b, and user ...

Unable to change the name of the file using ngx-awesome-uploader

Currently, I am utilizing https://www.npmjs.com/package/@sleiss/ngx-awesome-uploader and facing an issue regarding renaming files before uploading them. Upon reviewing the available methods, it appears that there is no option for file renaming. While I c ...

Angular: utilizing input type="date" to set a default value

Looking for a way to filter data by date range using two input fields of type "date"? I need these inputs to already display specific values when the page loads. The first input should have a value that is seven days prior to today's date, while the ...

The functionality of scrolling ceases to work once the bootstrap modal is closed

I am utilizing Bootstrap v3.1.1 to showcase a modal popup on one of my web pages. The following code shows how I have implemented it. <!--Start show add student popup here --> <div class="modal fade" id="add-student" tabindex="-1" role="dialog" a ...

What is causing the divs to not stretch across the entire width of the parent div?

Interactive Code Example: Snippet: <div style="width: 100%; overflow: hidden; height: 65px; background: #00CC00;"> <div style="width: 60%; overflow: hidden; float: left; background: #3074A3; color: #EDEDED; height: 65px; text-align: center; ...