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?
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With