Angular2:从组件中获取兄弟组件模板中的元素

时间:2017-06-30 04:19:05

标签: javascript angular angular2-template angular2-components

最近开始使用Angular2,遇到了以下情况

需要从兄弟组件访问元素,而不是从父Cmp访问元素。感谢您的关注

示例:

  • 假设我们有相同的组件A和组件B. 水平。

  • 需要ComponentB中templateA中的iframe元素隐藏或
    删除元素。

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

3 个答案:

答案 0 :(得分:0)

您可以使用@ViewChild来获取兄弟组件。所以你的Component 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

答案 1 :(得分:0)

有几种方法可以在兄弟姐妹之间共享数据:

  • 使用共享服务:几个月前我曾问过类似的问题。看看这里: share data using service
  • 使用父级进行通信:您可以为这些兄弟组件创建父组件,然后兄弟可以使用此父组件进行通信。因此,您的数据传输将以 sibling1 - &gt;父母 - &gt; sibling2 即可。更多详情:Component Interaction

答案 2 :(得分:-1)

我当然不想直接从组件B访问该元素,您希望将它们分离。

解决这个问题的两种可能方法是:

  • 使用包含切换的服务来隐藏或显示iframe。
  • 或者您可以使用事件机制从中触发事件 组件A侦听的组件B,它切换iframe 相应的元素。
相关问题