Search code examples
angulartypescriptradio-buttonangularjs-ng-clickng-class

How to add corresponding classes to the body element when each radio button is clicked in Angular 6


I want to add a specific class to the body tag and active class to the parent element when I click on each radio buttons.

Eg:

<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>

When I click the radio button with the value 'layout1', a class 'a' should be added to the body tag and it should change to class 'b' and 'c' accordingly when I click on each radio buttons.


Solution

  • 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>
    

    Example:https://stackblitz.com/edit/angular-7ffxib