Adding corresponding classes to the body element based on the selected radio button in Angular 6

Is there a way to dynamically add a class to the body tag and the parent element when clicking on radio buttons?

For example, consider the following code snippet:

<form action="">
 <input type="radio" value="layout1">Layout 1<br>
 <input type="radio" value="Layout2">Layout 2<br>
 <input type="radio" value="Layout3">Layout 3
</form>

Upon clicking the radio button with the value 'layout1', the body tag should receive a class 'a'. Subsequently, clicking on other radio buttons should change the class to 'b' and 'c' respectively.

Answer №1

import DOCUMENT from angular

import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';
  layout1;
  layout;
  layout3;

  constructor(@Inject(DOCUMENT) private document: any) { }   
  addClass($event) {
    if (this.document.body.classList) {
      let className = Object['values'](this.document.body.classList).filter(d => d !== $event);
      className.map(d => this.document.body.classList.remove(d));
      this.document.body.classList.add($event);
    }
    else {
      this.document.body.classList.add($event);
    }

  }

}

component.html

<form #f="ngForm">
 <input type="radio" value="a" (ngModelChange)="addClass($event)"[ngModel]="layout1" name="1"  ngModel>Layout 1<br>
 <input type="radio" value="b"(ngModelChange)="addClass($event)" [ngModel]="Layout2" name="1"  ngModel>Layout 2<br>
 <input type="radio" value="c" (ngModelChange)="addClass($event)" [ngModel]="layout3" name="1" ngModel>Layout 3
</form>

Visit this live example at:https://stackblitz.com/edit/angular-7ffxib

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

Tips for reducing redundant API requests while using NgRx

I'm facing an issue with my application that has 2 menu items; Teams and Players. Every time I switch between them, an unnecessary API call is made even though the data is already stored. Here is the effects file: loadTeams$ = createEffect(() => { ...

Display a FullCalendar showcasing events for the next 30 days

I am currently working with the FullCalendar library and I have a unique request. I need to create a rolling 30-day view using the month grid style, complete with day headers. Additionally, I need the flexibility to set the starting day in the grid. For ...

The historical state pushed through history is not accessible in the redirected class

Having a scenario where I need to redirect from one page to another and pass the state as a prop to the redirected page. I've utilized history.push and attempted to access it using console.log(this.props.location.state.searchString) but encountering a ...

When attempting to access the property 'originalname' of an undefined nodejs Mongoose object, an error is triggered

I am attempting to save images using mongoose, express, and multer. However, I keep encountering the following error when testing with Postman: TypeError: Cannot read property 'originalname' of undefined var express=require("express") var ro ...

The error message "Webpack is not applying the style from leaflet.css"

Currently utilizing the ngX-Rocket angular 8 starter, I am looking to integrate the leaflet map library into my project from this source: https://github.com/Asymmetrik/ngx-leaflet After including the file in my index.html document, I encountered the follo ...

Typescript and React encounter an error when trying to call a nested map function, stating that this expression is

Currently, I am working on a project using Typescript with React and encountering an issue with returning JSX from a function. Generally, I have not faced any problems with a nested map loop, but for some reason, I am getting an error when using Typescript ...

Discovering the url fragments (anchor parameters) using redirectTo in Angular routing

I am currently exploring Angular routing redirection using router tables and wondering if there is a straightforward way to include URL fragments in the redirect. My code snippet looks like this: { path: ':word', redirectTo: 'blah/:wor ...

quickest method for retrieving a property by name, regardless of its location within the object hierarchy

I am looking for a solution to retrieve the value of a property from an object graph, and I am wondering if there is a more efficient alternative to the method I have outlined below. Instead of using recursion, I have chosen tree traversal because it cons ...

Adding a timestamp or hash as a request parameter for css or js files in the NextJS 12 build file can be accomplished by simply including "?ts=[timestamp]" in the file

It is important for me to be able to generate the following JavaScript and CSS file names with timestamps after building a NextJs application: ./path/file.js?ts=[timestamp] ./path/file.css?ts=[timestamp] ...

Does client-side JS/Angular have an HTTP Connection Timeout feature?

I'm currently using Angular's HttpClient to send HTTP requests and I want to set a specific timeout for them. Although I am aware that I can utilize HTTPInterceptors and include a timeout in RxJS operators, these settings apply to the entire req ...

Challenges faced when using an array of objects interface in Typescript

I have initialized an array named state in my component's componentDidMount lifecycle hook as shown below: state{ array:[{a:0,b:0},{a:1,b:1},{a:2,b:2}] } However, whenever I try to access it, I encounter the following error message: Prop ...

Using ng-template in child component from Parent Component in Angular

I am facing a situation where I have a BaseComponent and IncomingRequestsComponent that inherit from BaseComponent. To utilize templates in components that inherit from BaseComponent, I need to include them in the HTML of BaseComponent. export class BaseTi ...

International replacement of external interface exportation

Currently, I am utilizing the @react-native-firebase/messaging library and invoking the method messaging().onNotificationOpenedApp(remoteMessage => ....) I am aiming to replace the property data within the type of remoteMessage in order to benefit from ...

Modifying the values of various data types within a function

Is there a more refined approach to enhancing updateWidget() in order to address the warning in the else scenario? type Widget = { name: string; quantity: number; properties: Record<string,any> } const widget: Widget = { name: " ...

Accessing the OSRM API allows users to determine the distance to the closest emergency station

I am currently working on a typescript project where I need to calculate the distance to the nearest police station and fire station. My approach involves utilizing typescript for this task. Initially, I attempted to use the following URL that I discovere ...

Is there a tidier method for coding this JSX?

Is there a way to optimize these function calls for both onGoClick and onNoGoClicked within the SomeForm component? Or is it fine to keep them as they are? <SomeForm onGoClick={() => { cleanupHere(props) }} o ...

What is the best way to fill a dropdown menu with the keys from an object?

Below is an example of the object I have: { "USD": { "symbol": "$", "name": "US Dollar", "symbol_native": "$", "decimal_digits": 2, "rounding": 0, "code": "USD", "name_plural": "US dollars" }, "CAD": { "symbol": "CA$" ...

How can I eliminate the white bar elements from my dropdown menu? Also, seeking guidance on replacing an empty <div> tag in a boolean query

Can anyone help me understand the strange white border around my dropdown menu and guide me on how to remove it? I am currently using DropdownButton from react bootstrap. I have attempted to adjust the CSS with no success. Here is the code I tried: .Navig ...

I'm encountering a Typescript error where I'm unable to assign a function to RefObject.current and it's indicating that the function is not callable

Does anyone know why assigning a function type to a ref.current type is causing me issues? useEffect(() => { savedHandler.current = handler; // ERROR HERE: }, [handler]); TS2741: Property 'current' is missing in type '(e: Chang ...

The Angular HTTP post request fails to get sent

I have a simple post method defined as follows: createTask(taskName: String, parentTaskId: String) : Observable<any>{ let headers : HttpHeaders = new HttpHeaders(); headers.set('Content-Type', 'application/json; charset=utf-8&a ...