JUSTIN JOSEPH
JUSTIN JOSEPH

Reputation: 21

How can I hide & Show a div element in a Component from 2 other components which don't have child parent relation?

In angular 2 app I have 3 different components Comp_A ,Comp_B and Comp_C. Comp_C has no parent child or sibling relation with other 2 components. Comp_B is the child of Comp_A. I am passing a button click event with EventEmitter through a sharedService to hide/show div block in Comp_C. in my code from Comp_A i can hide the div block in Comp_C. But unable to show the same div again from Comp_B with the help of same event emitter and shared service.

Upvotes: 0

Views: 3441

Answers (1)

JUSTIN JOSEPH
JUSTIN JOSEPH

Reputation: 21

    **Comp_C**
import {Component, OnInit} from 'angular2/core';
import {ComponentA} from 'src/ComponentA';
import {SharedService} from 'src/shared.service';
@Component({
    selector: 'my-app',
    templateUrl: './main-page.component.html',
    providers : [SharedService]
})

export class AppComponent implements OnInit {
  viewList : Boolean;

  constructor(ss: SharedService) {
      this.viewList = false;
      this.ss = ss;
    }



    ngOnInit() {
    this.subscription = this.ss.getEmittedValue()
      .subscribe(item => this.viewList=item);
  }

}

**main-page.component.html**

<div>
   <div *ngIf = " viewList == false">
       <mydata-list-component> </mydata-list-component>
   </div>
</dive>


----------


**Comp_A**

import {Component} from 'angular2/core';
import {SharedService} from 'src/shared.service';
@Component({
    selector: 'main-app',

    templateUrl: './menu-bar.component.html',

})

export class MainComponent {

    ss;

    constructor(ss: SharedService) {
      this.ss = ss;
    }

    hideListView() {
      this.ss.hide();
    }

}



**menu-bar.component.html.html**

<div>
   <button (click)="hideListView()">hideListView</button>
</dive>


----------

**Comp_B**

import {Component} from 'angular2/core';
import {SharedService} from 'src/shared.service';
@Component({
    selector: 'main-app',

    templateUrl: './menu-bar-sec-page.component.html',

})

export class MainComponent {

    ss;
    constructor(ss: SharedService) {
      this.ss = ss;
    }

    show ListView() {
      this.ss.show();
    }
}



**menu-bar.component.html.html**

<div>
   <button (click)="showListView()">hideListView</button>
</dive>


----------

**SharedService**


import {Component, Injectable,Input,Output,EventEmitter} from 'angular2/core'


@Injectable()
export class SharedService {
  @Output() fire: EventEmitter<any> = new EventEmitter();

   constructor() {
     console.log('shared service started');
   }

   show() {
    console.log('show started'); 
     this.fire.emit(false);
   }

   hide() {
    console.log('hide started'); 
     this.fire.emit(true);
   }

   getEmittedValue() {
     return this.fire;
   }

} 

Upvotes: 1

Related Questions