0

recently started Angular2, came across the below scenario

where need to access the element from a sibling component, but not from Parent Cmp. Thanks for looking at it

Example:

  • Let's say we have component A and component B which are on same level.

  • Need the iframe element in templateA in ComponentB to Hide or
    delete the element.

index.html

<component-A> </component-A>
<component-B> </component-B>

ComponentA.html

<div>
  <iframe id="someIframe"></iframe>
</div>

ComponentB.html

<div>
   <form id="someForm"></form>
</div>

@component

({
 selector:'component-A',
 templateUrl:'/componentA.html'

})

constructor() {

}

@component

({
 selector:'component-B',
 templateUrl:'/componentB.html'

})

constructor() {
 //need to get hold of the iframe element to hide that.
}
sridev9
  • 13
  • 3

3 Answers3

0

You can use @ViewChild to get ahold of the sibling component. So your Component B class should look something like this;

import {Component,ViewChild,AfterViewInit} from 'angular2/core';
import {ComponentA}         from './componentA';

@Component({
    selector: 'component-B',
    templateUrl: '/componentB.html'
})
export class ComponentB implements AfterViewInit{
    @ViewChild(ComponentA) 
    child:ComponentA; //say get the first instance of ComponentA

    ngAfterViewInit() {
        console.log(this.child); //access the child here
    }
}

Read more about @ViewChild here

HashanMadz
  • 61
  • 3
0

There are couple of ways you can share data between siblings:

  • using a shared service: I had asked a similar question a few months back. Take a look here: share data using service
  • Communicating using parent: You could create a parent component to these siblings and then sibling can communicate using this parent component. So your data transfer would happen as sibling1 -> parent -> sibling2. More details here: Component Interaction
mrsan22
  • 727
  • 2
  • 11
  • 28
-1

I would certainly not want to access the element directly from component B, you'll want to leave them decoupled.

2 possible ways of solving this is:

  • Using a service which contains a toggle to hide or show the iframe.
  • Or you could use an event mechanism where you fire an event from component B which component A listens to and it toggles the iframe element accordingly.
than
  • 817
  • 9
  • 13