【问题标题】:Angular2 : get hold of an element in template of a sibling component from a componentAngular2:从组件中获取兄弟组件模板中的元素
【发布时间】:2017-12-03 22:42:52
【问题描述】:

最近入手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>

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

【问题讨论】:

  • 是的,您可以使用输入和输出功能。

标签: javascript angular angular2-template angular2-components


【解决方案1】:

您可以通过多种方式在兄弟姐妹之间共享数据:

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

【讨论】:

    【解决方案2】:

    您可以使用@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

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2019-04-16
        • 2017-05-04
        • 2017-10-30
        • 2020-01-31
        • 2016-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-22
        相关资源
        最近更新 更多