Changes in the styles of one component can impact the appearance of other

When it comes to styling my login page, I have specific stylesheets that I include in login.component.ts. For all the common CSS files, I have added them in the root index ("index.html") using the traditional method. However, after a user logs into the system, I expect the app.component.css file to take control of the body and change the background color. Strangely, the background color remains as it was on the login page.

The strange thing is, when I refresh the page (reload), the issue disappears. However, the main attraction of using Angular 2 is the ability to create single-page apps without the need for refreshing. So, how can I handle this problem?

Below is an excerpt from my login.component.ts:

import { Component, HostBinding, ViewEncapsulation } from '@angular/core';
import { Auth } from '../auth/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: [
    '../../assets/css/colors/cyan.css',
    '../../assets/css/login-page/form.css',
  ],
  encapsulation: ViewEncapsulation.None,
})
export class LoginComponent {

  @HostBinding('class') siteNavbarSmallClass = 'login-form login-form-second page-login-second';
  constructor(private auth: Auth) {}
}


And here is a snippet from app.component.ts:

import { Component, HostBinding, ViewEncapsulation } from '@angular/core';
import { Auth } from './auth/auth.service';

@Component({
  selector: 'body',
  templateUrl: './app.component.html',
  styleUrls: [
    'assets/css/global/slidePanel.min.css',
    'assets/css/colors/default.css',// this is the css file I want to use for others.
  ],
  encapsulation: ViewEncapsulation.None, 
})
export class AppComponent {
  @HostBinding('class') siteNavbarSmallClass = 'dashboard site-navbar-small';
  constructor(private auth: Auth){}
}

In summary, even after thorough investigation with screenshots, the issue persists - the CSS attributes for the body element remain unaffected by the changes made in the app.component. Below are some visuals to illustrate the problem:

Login Page:

https://i.sstatic.net/YZdkG.png

After Logging In:

https://i.sstatic.net/I6csB.png

After Reloading (Expected Outcome):

https://i.sstatic.net/JSjxm.png

If anyone has any insights or solutions on how to prevent the CSS properties of the login component from affecting other components (specifically app.component), your help would be greatly appreciated!

Answer №1

Encapsulation is key: Try using ViewEncapsulation.Emulated for your login component and any others where you want to keep the css contained.

If you don't define the encapsulation behavior, Emulated will be used by default.

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

Angular's DomSanitizer not functioning properly with the Transform css property

I have a question regarding my use of DomSanitizer. The background css property seems to be working fine, but the transform property is not displaying any output. I'm unsure where I might be going wrong in my implementation. In my Angular 8 code: i ...

Utilize a personalized npm script to change the name of a file

I need some help with creating a script for my angular2 project that will rename README.md to README_2.md. After installing "renamer" : "0.6.1", I tried making this script: "renameMd": "renamer --find js/README.md --replace js/README_2.md" in my package.j ...

What could be causing my TSC to constantly crash whenever I try to utilize MUI props?

Currently in the process of converting a JavaScript project using Next.js and Material UI to TypeScript. This is a snippet of code from one of my components. Whenever I include Props as an intersection type along with MUI's BoxProps, the TypeScript c ...

'Watch for status within resolver's state (ngrx)'

Currently, I am using a resolver that calls a standard service and returns an Observable: return this.someService.getData() .map(data=> data.json()) I am looking to replace this setup with ngrx effects and store. In the resolver, I want to dispa ...

What is the best way to incorporate "thread.sleep" in an Angular 7 app within a non-async method like ngOnInit()?

Despite the numerous questions and solutions available on Stack Overflow, none of them seem to work when called from a component's init function that is not asynchronous. Here's an example: private delay(ms: number) { return new Promise( ...

Installing a 3rd party plugin in Angular using the Angular-cli tool

When attempting to install angular2-grid on my Angular-cli with version 2.0.0-rc.1, I followed the tutorial exactly as described but encountered an error. zone.js:101 GET http://localhost:4200/node_modules/angular2-grid/dist/NgGrid 404 (Not Found)sche ...

The component does not contain the specified property

One Angular 4 component that I have is like this: export class MenuComponent { constructor(private menuService: MenuService) { } @Input(nodes):any; getMenu(path:string): void { this.menuService.getData(path).subscribe(data => { // Re ...

Having difficulty maintaining trailing zeroes in decimals after converting to float in Angular

I need assistance with converting a string to float in Angular. Whenever I use parseFloat, it seems to remove the zeros from the decimal values. How can I ensure that these zeros are retained with the numerical values? The example below should provide more ...

How can I retrieve all the data for the chosen item in a mat-select within a mat-dialog, while still preserving the code for setting the default selected value

In my modal dialog, I have a dropdown menu populated with various languages. The ID of the selected language is bound to the (value) property for preselection purposes when data is passed into the dialog. However, I am looking for a way to also display the ...

Utilize Typescript with React to efficiently destructure and spread objects

My goal is to maintain my child components as stateless (functional components). Therefore, I am in search of an efficient way to pass down the root component's state values to its children. For example, interface IState { a: string; b: number; ...

Stop the direct importing of modules in Angular applications

I have a feature module that declares components and also configures routing through a static function. @NgModule({ declarations: FEATURE_COMPONENTS, entryComponents: FEATURE_COMPONENTS, imports: [ UIRouterModule, ... ] }) export class Fea ...

Guide on Integrating RDLC Reports with Angular 7

I currently have a window application that contains multiple RDLC reports. As I am transitioning this window application to Angular 7, I am wondering if there is a way to utilize my existing RDLS reports in Angular 7? While I have come across suggestion ...

TypeScript: Defining a custom object type using an array of objects

Is there a way to dynamically generate an object based on the name values in an array of objects? interface TypeA { name: string; value: number; } interface TypeB { [key: string]: { value: any }; } // How can we create an OutputType without hard ...

Any ideas for handling ProtractorJS timeouts while clicking an element?

The Issue at Hand I am currently facing a challenge with clicking a straightforward 'New Booking' button in my Angular 5 Material 2 Application. The code snippet for the button is as follows: <button _ngcontent-c9="" class="mat-menu-item" ma ...

A guide on integrating a vue-concurrency Task Creator with argument support

I've been grappling with my Vue 3 / TypeScript app and the vue-concurrency library. Everything is nearly in place, but configuring a Task Creator to accept arguments has proven to be quite challenging. Following the Task Creators pattern outlined in ...

parsing objects within an HTML component in Angular

Is there a way to utilize an object as the @input parameter in HTML? For example: <app-home [param]="user.salary"></app-home> However, the type of my user object is structured like this: user:Person=new Employee(); The classes invol ...

Wondering how to leverage TypeScript, Next-redux-wrapper, and getServerSideProps in your project?

Transitioning from JavaScript to TypeScript for my codebase is proving to be quite challenging. // store.ts import { applyMiddleware, createStore, compose, Store } from "redux"; import createSagaMiddleware, { Task } from "redux-saga"; ...

Error in Vue 3 Script Setup with Typescript: Implicit 'any' type for parameter 'el' in Template ref

Could someone help explain why I am receiving an error from TypeScript that says the following? error TS7006: Parameter 'el' implicitly has an 'any' type. ref="(el) => saveRef(index, el)". I am confident that the correct type is set ...

Error in Angular: The type 'Response' is not generic

Currently, I am attempting to extract a nested array from an HTTP response with Angular 14 getItems(): Observable<Item[]> { return this._httpClient.get<Item[]>(this.apiUrl + 'items').pipe( tap((items) => { t ...

What is preventing TypeScript from automatically inferring the type of an argument in a generic function that utilizes `keyof`?

What causes the error in this code snippet? type MyType = { a: string, b: string } function cantInfer<In, Out>(fn: (i: In) => Out, i: In) { } function myFunction<K extends keyof MyType>(key: K): string { return ''; } ...