Home > Software design >  Angular after click add active class and remove from siblings
Angular after click add active class and remove from siblings

Time:12-23

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  (click)="select($event)">
    <div >
        <h4 >{{itemlistDesc.name}}</h4>
        <p><span >{{itemlistDesc.unit}}</span> Units at ${{itemlistDesc.price}}/Units</p>
    </div>
    <div >
        <div >
            {{(itemlistDesc.price * itemlistDesc.unit)}}$
        </div>
    </div>    
</div>

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

CodePudding user response:

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  (click)="select($event)" [ngClass]="{'active': itemlistDesc.is_active}">

</div>

CodePudding user response:

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

  • Related