Chuka32
Chuka32

Reputation: 25

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

<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+)

Upvotes: 0

Views: 1724

Answers (2)

Ashish Yogi
Ashish Yogi

Reputation: 96

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>

Upvotes: 1

Deepak Jha
Deepak Jha

Reputation: 1609

If you are passing some params in the component you can make use of ngClass and conditionally put and remove classes, check this,

ngClass documentation

Upvotes: 1

Related Questions