繁体   English   中英

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

[英]Angular2 : get hold of an element in template of a sibling component from a component

最近启动Angular2,遇到以下情况

需要从同级组件而不是从Parent 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>

@零件

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

})

constructor() {

}

@零件

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

})

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

您可以使用@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的更多信息

您可以通过几种方法在同级之间共享数据:

  • 使用共享服务 :几个月前,我曾问过类似的问题。 在这里看看: 使用服务共享数据
  • 使用父级进行通信 :您可以为这些同级创建父级组件,然后同级可以使用此父级组件进行通信。 因此,您的数据传输将以sibling1-> parent-> sibling2进行 此处有更多详细信息: 组件交互

我当然不希望直接从组件B访问元素,而是要使它们脱离耦合。

解决此问题的2种可能方法是:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM