Assign a value to the class attribute of the body element using ngClass

Currently, I am trying to change the value of a class based on whether a user is signed in or not. I have checked the code in both app.component.ts and login.component.ts as shown below;

app.component.ts

export class AppComponent {
  isAuthenticated:boolean;
  constructor(private auth:Auth){
      this.isAuthenticated=this.auth.authenticated();
  }
}

login.component.ts

 export class LoginComponent {
  isAuthenticated:boolean;   
  constructor(private auth:Auth){
    this.isAuthenticated=this.auth.authenticated();
  }
}

and index.html

<body [ngClass]="{
  'dashboard site-navbar-small' :isAuthenticated,
  'login-form login-form-second page-login-second' :!isAuthenticated
}">
  <app-root>Loading...</app-root>

Unfortunately, it seems that the changes are not being applied correctly. Here is how it appears in the browser: https://i.sstatic.net/Zl8EA.png

Answer №1

Have you considered refactoring the logic out of the constructors and into separate functions instead? How do you envision this working? Can you elaborate on the specifics of the code logic?

app.component.ts

export class AppComponent {
  isLoggedIn: boolean = false;

  private toggleLoginStatus(){
     this.isLoggedIn = !this.isLoggedIn;
  }
}

login.component.ts

 export class LoginComponent {
  isLoggedIn: boolean = false; 

   private toggleLoginStatus2(){
     this.isLoggedIn = !this.isLoggedIn;
  }
}

index.html

<body [ngClass]="{ 
  'dashboard site-navbar-small': isLoggedIn,
  'login-form login-form-second page-login-second': !isLoggedIn
}">
</body>

Edit

It seems like you are trying to assign a function to a boolean variable. Is this the intended approach?

this.isLoggedIn = this.auth.isAuthenticated();

Answer №2

In the structure of an angular application, the root component is located within the body tag. This means that direct binding to the body tag is not possible. More information can be found in the Angular 2 documentation.

Currently, Angular provides the Title service as a way to manage the title of the page.

export class AppComponent {
  title = 'app works!';
  public constructor(private titleService:Title){
    this.titleService.setTitle('My ToDo');
  }

If you need to manipulate the body tag, you can use setElementClass on plunker, or alternatively, utilize JQuery.

setElementClass(document.body, "dashboard site-navbar-small", isAuthenticated)
setElementClass(document.body, "login-form login-form-second page-login-second", !isAuthenticated)

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

Can you explain the distinction between 'rxjs/operators' and 'rxjs/internal/operators'?

When working on an Angular project, I often need to import functionalities like the Observable or switchMap operator. In such cases, there are two options available: import { switchMap } from 'rxjs/operators'; or import { switchMap } from ' ...

When triggering the event: Was anticipating a spy, however received a Function instead

Upon running my test, I encountered the following error message: Error: Unhandled Promise rejection: <toHaveBeenCalledWith> : Expected a spy, but received Function. it('should change the value of myComponent', () => { spyOn(component ...

Testing an Angular component using Jasmine within a project with multiple module files

Struggling to troubleshoot an issue I'm facing with my testing setup. The service tests that rely solely on the httpclient are running smoothly. However, when attempting to test a component with dependencies, errors start popping up without even execu ...

Sharing data between components in Angular 4: Passing objects between different parts of your

Exploring Angular 4 development using TypeScript: I am looking to establish a static object in app.component.ts that can be accessed in all components. Any suggestions on how to accomplish this? ...

Using an Object as a Key in Maps in Typescript

I had the intention of creating a Map object in Typescript where an object serves as the key and a number is the value. I attempted to define the map object in the following manner: myMap: Map<MyObj,number>; myObj: MyObj; However, when I tried to a ...

Combining data types to create a unified set of keys found within a complex nested structure

This problem is really testing my patience. No matter what I do, I just can't seem to make it work properly. Here's the closest I've come so far: // Defining a complex type type O = Record<'a', Record<'b' | 'x& ...

Angular - Navigate to Login Page post registration and display a confirmation message

As a newcomer to Angular, I am currently working on an Angular and Spring Boot application. So far, I have created components for user login and registration along with validation features. Now, my goal is to redirect the user to the login page upon succes ...

What is the process for implementing a type hint for a custom Chai assertion?

As part of my typescript project, I decided to create a custom assertion for the chai assertion library. Here is how I implemented it: // ./tests/assertions/assertTimestamp.ts import moment = require("moment"); import {Moment} from "moment"; const {Asser ...

I am experiencing an issue with mydaterangepicker and primeng where it is not displaying properly in the table header. Can anyone assist me with this

I am attempting to integrate mydaterangepicker () with primeng turbotable (since primeng calendar does not meet the requirements), but I am having trouble with its display. Could you please assist me with some CSS code or suggest an alternative solution? ...

Even though the Web API has CORS Policy set up, it is still being blocked

I am currently working on an ASP.NET Core Angular application. I have added an API Controller in the Core app and am attempting to make an API call from the Angular app. The Core app is hosted on port 58181 and the Angular app on port 44337. However, when ...

Combining SignalR and Angular: Steps for incorporating a Bearer token into Http Headers

Recently, I developed an asp.net core 2.0 SignalR Hub that utilizes a Bearer Token for Authentication. However, I am encountering some confusion when trying to establish a connection with the SignalR Angular 5 client. Interestingly, the connection succeeds ...

I was unable to showcase various maps

import TileLayer from 'ol/layer/Tile'; import OSM from 'ol/source/OSM'; layers: any; base_maps:any; map = new Map({ target: 'map', layers: [ new TileLayer({ source: new OSM({ maxZoom: 23, }), ...

Create a class with additional attributes to support different types of options

I define a set of options represented by strings: export type Category = 'people' | 'projects' | 'topics' | 'tools' An index is declared as follows: interface Entry { ... } type IPostEntryIndex = { [name in Cate ...

Can you explain the distinction between inheritance and union types in regards to portraying polymorphism?

Exploring union types in Typescript, I have discovered a new way to showcase polymorphism without relying on inheritance. In my previous Java background, I would typically approach it like this: interface Emotion { display(): string; } class Joy impleme ...

Exploring the Functionality of HTML Anchor Link Fragment within Angular 6

I've been working on an Angular 6 project where I've disabled the hash-location-strategy, removing # from the URL. As a result of this change, a link like: <li routerLinkActive="active"> <a [routerLink]="['/settin ...

What could be the reason for the Angular dropdown values not appearing?

Encountering an issue with binding data to a dropdown element, as the dropdown displays NOTHING SELECTED. <select #classProductTypeCombobox name="classProductTypeCombobox" class="form-control col-md-3" [(ngModel)]="classifica ...

I am unable to get the radio button checked in Angular 2

I have set up a form with two radio buttons for gender selection, and I want to ensure that the previously selected option is displayed as checked. Here's the code snippet I've added in my template: <div class="form-group"> <label& ...

Problem with Extending Jest Matchers in VS Code TypeScript

I've developed unique Jest matchers to enhance expect for handling AxiosResponse objects. Although I've followed the standard method for expanding Jest's matcher types, my custom matchers are not being recognized by TypeScript. The error di ...

Challenge with React CloneElement regarding typing

Utilizing React Children and React Clone element, I aim to trigger methods in both the wrapper and Select components upon onClick event in the Option component. Although everything is functioning correctly, I am encountering a type error when calling the O ...

Issues with hydrating React local storage hook in custom implementation within NextJS

Currently facing an issue while implementing the localstorage hook in NextJS. The error message I am encountering is: Error: Hydration failed because the initial UI does not match what was rendered on the server.. Any suggestions on what might be causing ...