0

得到同级组件的模板元素的保留最近开始Angular2,横跨下面的情形Angular2:从组件

哪里需要从同级组件访问元素来了,但不从父CMP。感谢看着它

例子:

  • 比方说,我们有A成分和B,其在同级别 。

  • 需要ComponentB中的templateA中的iframe元素为Hide或
    删除该元素。

的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. 
} 
+0

是的你可以使用输入和输出功能。 –

回答

-1

我肯定不会想直接从成分B访问元素,你要离开他们去耦。解决这个的

2种可能的方式是:

  • 使用包含间的切换显示或隐藏的iframe的服务。
  • 或者您可以使用事件机制从组件A发出事件 组件B,组件A将侦听并相应地切换iframe 元素。
0

您可以使用@ViewChild来查看兄弟组件。所以你的组件B类应该看起来像这样;

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 
    } 
} 

了解更多关于@ViewChild here

0

有几个方法可以兄妹之间共享数据:

  • 使用共享服务:我问过类似的问题几几个月前。看看这里: share data using service
  • 使用父母沟通:您可以创建一个父组件,然后兄弟姐妹可以使用此父组件进行通信。因此,您的数据传输将以sibling1 - > parent - > sibling2发生。更多细节在这里:Component Interaction