How can I use shared variable among different *ngFor iteration of angular 2 component

288 views Asked by At

I've a list and list have many elements and each element is an angular 2 component i.e. ElementComponent. I am listing list elements(ElementComponent1) using *ngFor. What the condition is, when click on an element, particular div is displayed and when I click on another ElementComponent2 the open div needs to be closed and open a new div with element 2 data.

But when I click on another component then this.variable reference get changed and the new div is opened over the old one.

Is there any shared variable functionality that I can use among iteration of the components

I am adding code screens- Adding the component using *ngFor

<span *ngFor="let card of list.cards; let i = index" class="card card_list">
<element id="{{card.id}}" [data]="card"></element>

element.component.js

/*jshint esversion: 6 */

import { Component, Input, ViewChild, Pipe } from '@angular/core';
import {BrowserModule} from '@angular/platform-browser'

import DynamicComponent from '../dynamic/dynamic.component';
import {SharedService} from '../../services/shared.service';

@Component({
    selector: 'element',
    templateUrl: "app/components/element/element.component.html"
})
export class ElementComponent {

    @Input('data') element;


    cardDescriptionShow(element) {

        this.list_data = element;
        this.description = true;
    }

    cardDescriptionHide() {
        this.description = false;
    }

}

element.component.html

<a class="card_list_title" (click)="cardDescriptionShow(element)" >{{element.title}}
</a>

<div *ngIf="description" class="card_desc pd_20" id="test">
    <div class="m_btm10">
        <span class="glyphicon glyphicon-th-list"></span><span class="card_desc_heading">{{list_data.title}}</span>
        <a class="card_list_title" (click)="cardDescriptionHide()" ><span class="glyphicon glyphicon-remove"></span></a>
    </div>

    <div class="list_card_description">
        <description></description>
    </div>
</div>
0

There are 0 answers