Angular2:从父级获取子组件上的elementref
我正在尝试从父组件获取子组件的ElementRefAngular2:从父级获取子组件上的elementref,angular,Angular,我正在尝试从父组件获取子组件的ElementRef @Component({ moduleId: module.id, selector: 'parent', templateUrl: 'parent.component.html', directives: [ Child1Component, Child2Component ] }) 在Child1Component的html中,我有 <button class="btn btn-primary" #myRef>
@Component({
moduleId: module.id,
selector: 'parent',
templateUrl: 'parent.component.html',
directives: [
Child1Component,
Child2Component
]
})
在Child1Component
的html中,我有
<button class="btn btn-primary" #myRef>Select File</button>
当然,当我试图访问父类中的子ElementRef时
ngAfterViewInit() {
console.log(this.myRef.nativeElement);
…我得到
未定义的。我应该如何获得ElementRef?谢谢 尝试使用ContentChild而不是ViewChild
import { Component, ContentChild, ElementRef, OnInit } from '@angular/core';
...
export class ParentComponent implements OnInit {
@ContentChild('myRef') myRef: ElementRef;
// ...
ngAfterViewInit() {
console.log(this.myRef.nativeElement);
}
}
你现在可以这样做了
@ViewChild('myRef', {read: ElementRef}) myRef: ElementRef
默认情况下,如果模板引用变量附加到自定义组件,Angular将获取组件引用。read
选项告诉angular要拉哪个标记,因此,您可以显式地告诉它提取ElementRef
标记,而不是尝试读取的任何组件的类实例。我不知道父组件能够引用子组件模板中定义的本地模板变量的任何方法。考虑让父对象使用@ VIEWHORD获得对子组件的引用,那么您可以调用子组件上的方法来操纵感兴趣的元素。@克里斯:您在您的最后一个评论是完全不需要的,是一种可以阻止您从这个站点被禁止的评论。已通知版主您的行为。
@ViewChild('myRef', {read: ElementRef}) myRef: ElementRef