Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular after click add active class and remove from siblings

Using component for list how to add active class and remove it from siblings.

//in main component Html

<app-item-desc *ngFor="let itemDesc of addedItem; let i = index" [itemlistDesc]="itemDesc"></app-item-desc>

//list’s component

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div class="order" (click)="select($event)">
    <div class="order__left">
        <h4 class="order__title">{{itemlistDesc.name}}</h4>
        <p><span class="order__unit">{{itemlistDesc.unit}}</span> Units at ${{itemlistDesc.price}}/Units</p>
    </div>
    <div class="order__right">
        <div class="order__total">
            {{(itemlistDesc.price * itemlistDesc.unit)}}$
        </div>
    </div>    
</div>

is there a possible way to use directive? (Angular 2+)

>Solution :

In your problem, issue is your array is in parent component and you want active class in child component.
To remove active class from other array elements you have to pass event to a parent component to make active class false from the other one.

In the child

import { Output, EventEmitter } from '@angular/core';
@Output() itemSelectEvent= new EventEmitter<string>();

select(array_item){
itemSelectEvent.emit(array_item.id);
}

In Parent Needs to handle that event

<app-item-desc *ngFor="let itemDesc of addedItem; let i = index" [itemlistDesc]="itemDesc" (itemSelectEvent)="selectEventHandler($event)"></app-item-desc>

selectEventHandler(event){
 // event, you will get selected id here
 for(let i=0;i < addedItem.length;i++){
   if(addedItem[i].id == event){
    addedItem[i]['is_active'] = true;
   }else{
    addedItem[i]['is_active'] = false;
   }
 }
}

In the child you can use is_active add directive now

<div class="order" (click)="select($event)" [ngClass]="{'active': itemlistDesc.is_active}">

</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading