[英]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的更多信息
我當然不希望直接從組件B訪問元素,而是要使它們脫離耦合。
解決此問題的2種可能方法是:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.