簡體   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