Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the reference of all elements in a div in Angular 2?

I have a div with 10 HTML elements. How could I get the reference of all these 10 elements and toggle a class on them on click?

<div>
 <some-element class="hawk"></some-element>
 <some-element class="hawk"></some-element>
 <some-element class="hawk"></some-element>
 <some-element class="hawk"></some-element>
 <some-element class="hawk"></some-element>
...
</div>
<div class="trigger" (click)="detach()">Detach</div>

SCSS:

.hawk {
    display: block;
    width: 16px; 
    height: 16px;
    border-radius: 10px;
    line-height: 12px;
    cursor: pointer;
    &.mock {
        border-radius: 0px;
    }
 }

I can do this very easily by using jQuery as follows:

detach() {
  $('.hawk').toggleClass('mock');
}

What is the angular way of doing it? I tried using the @ViewChild and access the parent div but I was unable to add the class to all the child elements. While changing the border-radius to 0px, is there a way to animate from the set 10px to 0px in CSS or using Angular animations?

like image 282
zelda Avatar asked May 14 '18 21:05

zelda


Video Answer


2 Answers

As @tjadli mentioned, @ViewChildren is the way to go. But I think his toggling logic is a bit convoluted. You can simply do the following:

@ViewChildren('hawk', {read: ElementRef}) ref: QueryList<ElementRef>;

HTML:

<div>
 <some-element #hawk class="hawk"></some-element>
 <some-element #hawk class="hawk"></some-element>
 <some-element #hawk class="hawk"></some-element>
 <some-element #hawk class="hawk"></some-element>
 <some-element #hawk class="hawk"></some-element>
...
</div>
<div class="trigger" (click)="detach()">Detach</div>

Function:

detach() {
  this.ref.map((eleRef) => {
  if(eleRef.nativeElement.classList.contains('hawk')) {
    eleRef.nativeElement.classList.toggle('mock');
  }
 });
}

Hope this helps.

like image 88
ShellZero Avatar answered Oct 11 '22 06:10

ShellZero


First of all instead of using ViewChild you have to use ViewChildren

detach() {
    this.hawks.map((elmRef) => {
       if(elmRef.nativeElement.className === 'hawk') {
          elmRef.nativeElement.className = '';
       } else {
          elmRef.nativeElement.className = 'hawk';
       }
    })
}

and for your viewchildren :

@ViewChildren('hawk', {read: ElementRef}) hawks: QueryList<ElementRef>;

and your html :

<some-element #hawk class="hawk"></some-element>
<some-element #hawk class="hawk"></some-element>
<some-element #hawk class="hawk"></some-element>
like image 31
tjadli Avatar answered Oct 11 '22 08:10

tjadli