Search code examples
angularangular5renderer

Angular 5 remove class using wildcard


I have an input attribute with a class :

<input class="color b1 b2 b3" text="text">

I want to remove all the classes after color so i can add other classes. But how to do it with a wildcard using .renderer.removeClass ? So far i do this which is redundant and not clean

// remove class
this.renderer.removeClass(this.elRef.nativeElement.querySelector(".color"), 'b1');
this.renderer.removeClass(this.elRef.nativeElement.querySelector(".color"), 'b2');
this.renderer.removeClass(this.elRef.nativeElement.querySelector(".color"), 'b3');
// add class
this.renderer.addClass(this.elRef.nativeElement.querySelector(".color"), 'b4');

I tried something like this but with no success :

 this.renderer.removeClass(this.elRef.nativeElement.querySelector(".color"), 'color*');

Solution

  • You can remove all the classes of an element matching the regex as follows :

    let el = this.elRef.nativeElement.querySelector(".color");
    let regex = /^b\d$/;
    let classes = el.getAttribute('class').split(' '); // get all classes
      classes.forEach((cl) => {
           if(cl.match(regex)) {  // match classes b1, b2, b3....
             this.renderer.removeClass(el, cl);
           }
      });
    this.renderer.addClass(el, 'b4');
    

    See this working code