Learn how to add and remove a class name to an element with angular

Learn how to add and remove a class name to an element with angular

 


We can able to add and remove a class to an element in angular. In the following example, we have added/removed a class for the input element using a button component.

 

Example :

 

Video tutorial : https://youtu.be/vMM05geNQJ4

 

[app.component.html]

<input class="myInput" type="text" value="subscribe for more videos" />

<br />

<button (click)="addClass()" class="button">Add Class</button>

<button (click)="romveClass()" class="button">Remove Class</button>

 

[app.component.css]

.myInput {

  font-weightbold;

}

.inputStyle {

  width300px;

  colorcoral;

  border-radius5px;

  height25px;

  padding3px;

}

.button {

  coloraliceblue;

  background-colorrgb(5163255);

  bordernone;

  width100px;

  height30px;

  border-radius5px;

  margin10px;

}

 

[app.component.ts]

import { ComponentVERSION } from '@angular/core';

 

@Component({

  selector: 'my-app',

  templateUrl: './app.component.html',

  styleUrls: ['./app.component.css'],

})

export class AppComponent {

  addClass() {

    document.getElementsByClassName('myInput')[0].classList.add('inputStyle');

    alert('Class added');

  }

  romveClass() {

    document

      .getElementsByClassName('myInput')[0]

      .classList.remove('inputStyle');

    alert('Class removed');

  }

}

 

Sample https://stackblitz.com/edit/angular-ivy-pgtw4g?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.css

Comments