[英]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.