Reputation: 129
I have just started coding in angular5 and I came across need of removing all class occurances on click event. Something like below we have in Jquery
$('.m-active').removeClass('m-active');
I am looking for alternative of this in angular2 + (Typescript)
Upvotes: 0
Views: 3356
Reputation: 28610
You can create a directive like this :
https://plnkr.co/edit/eKokX0IrsIWIuY9ACUZ4?p=preview
@Directive({
selector: '[class]'
})
export class ClassDirective {
@Input('class') claz;
private _claz;
public set claz(claz){
this._claz = claz;
}
public get claz(){
return this._claz;
}
@HostBinding('class') get hostClass(){
return this.claz;
}
constructor(){
console.log('***');
}
ngOnInit(){
console.log('this.classz',this.claz);
setTimeout(()=>{
this.claz= this.claz.replace('milad','');
},2000)
}
}
I know it doesn't do exactly what you want, but the idea is to create a Directive which has a selector called class
and then you have access to all the classes in your application (obviously this component should be declared in your modules).
Then you can do whatever you'd like inside that directive, you can use host binding to override the classes and whatnot.
You can create an event listener to some button, pass the event listener's call back to this directive and let it do whatever you want.
Upvotes: 0
Reputation: 15519
You could use document.querySelector all to remove the class - in the following - I have two divs - iniitally set to be red / green text, but using querySelectorAll - I am removing the red class from the divs.
function toggleRedClass() {
var redDivs = document.querySelectorAll('.red');
if (redDivs.length) {
for(i=0;i<redDivs.length;i++) {
redDivs[i].classList.remove('red');
redDivs[i].classList.add('black')
}
} else {
var blackDivs = document.querySelectorAll('.black');
for(i=0;i<blackDivs.length;i++) {
blackDivs[i].classList.remove('black')
blackDivs[i].classList.add('red')
}
}
}
.red {color:red}
.green {color:green}
<div class="red">test</div>
<div class="green">test1</div>
<button type="button" onclick="toggleRedClass()">Click to toggle the red class</button>
Upvotes: 2
Reputation: 658263
In Angular 2+ better use bindings instead of jQuery
<div [class.my-class]="isMyClass">div 1</div>
<div [class.my-class]="isMyClass">div 2</div>
<button (click)="isMyClass = !isMyClass">toggle</button>
export class MyComponent {
isMyClass:boolean = true;
}
Upvotes: 1