valerio0999
valerio0999

Reputation: 12138

click anywhere to remove a class in angular2

im on angular2+ and i have an element that has an active class, such as

<div class="notification active">...</div>

what i need to do is that, if i click/tap on anything except on that div the active class should be removed.

similarly to this jquery example: https://codepen.io/vlrprbttst/pen/xOoxWo

i had a hard time figuring out how to add that active class and now i have no idea on what's the approach to remove it, and especially how to typescript the "click anywhere to..." part. :/

i am not interested in detecting if that class is there or not as in this question: remove or add Class in Angular and the main difficulty is not removing the class i guess, but the "click anywhere to remove it" part.

any help is greatly appreciated

Upvotes: 1

Views: 1746

Answers (2)

P0wersl4ve
P0wersl4ve

Reputation: 65

You could achieve that by doing something like this, using NgClass.

component.html

<div (click)="clicked=!clicked" [ngClass]="clicked ? 'active' : 'hidden'">                
     Your content goes here
</div>

So now define your active and hidden css classes like this in your

component.scss

.active {
    display: block;
}

.hidden {
    display: none;
}

That should do the trick :)

Upvotes: -1

terahertz
terahertz

Reputation: 3511

Sorry for the flag earlier, didn't read your question thoroughly enough. Anyway, like Rich had mentioned, what you're trying to do is quite similar to jQuery/javascript if you come from that background (like most of us do).

export class AppComponent  {
  name = 'Angular';

  constructor(private eleRef: ElementRef){

  }

  ngAfterViewInit() {
    this.eleRef.nativeElement.querySelector('main').addEventListener('click', this.onClick.bind(this));
  }

  onClick(event: MouseEvent){
    // console.log(event.target)
    let clickedEle = event.target as HTMLElement;
    let aBoxEle = this.eleRef.nativeElement.querySelector('#aBox') as HTMLElement;
    if(clickedEle.id != "aBox"){
      if(aBoxEle.classList.contains("box")){
        aBoxEle.classList.remove("box");
      }else{
        aBoxEle.classList.add("box");
      }
    }
  }
}

You can try it out with this stackblitz example 🚀

Also, do have a read on this: “Thinking in AngularJS” if I have a jQuery background?. To be able to use Angular effectively, you have to "unlearn" some parts of jQuery that you are used to.

Upvotes: 3

Related Questions