I have a component with the name EasyBoxComponent
,
and a @Directive
with this @Viewchild
:
@ViewChild(EasyBoxComponent) myComponent: EasyBoxComponent;
I thought this was the correct syntax, but this.myComponent
is always undefined.
Here's the whole code:
<my-easybox></my-easybox>
<p myEasyBox data-href="URL">My Directive</p>
import { Directive, AfterViewInit, HostListener, ContentChild } from '@angular/core';
import { EasyBoxComponent } from '../_components/easybox.component';
@Directive({
selector: '[myEasyBox]'
})
export class EasyBoxDirective implements AfterViewInit {
@ContentChild(EasyBoxComponent) myComponent: EasyBoxComponent;
@ContentChild(EasyBoxComponent) allMyCustomDirectives;
constructor() {
}
ngAfterViewInit() {
console.log('ViewChild');
console.log(this.myComponent);
}
@HostListener('click', ['$event'])
onClick(e) {
console.log(e);
console.log(e.altKey);
console.log(this.myComponent);
console.log(this.allMyCustomDirectives);
}
}
myComponent
? – Readiness@ViewChild()
is pointless. Try@ContentChild()
instead. If it doesn't work, please provide more code that demonstrates what you try to accomplish. – CaelianContentChild()
or@ViewChild()
to query something outside of the component. Only projected content (as the textMyDirective
is) or direct children within a components view.<my-easybox>
is a sibling to the element that has the directive. Angular doesn't provide a way to query it. You can usequerySelector
but there are probably better ways. But I would need to understand the actual problem you're trying to solve better to be able to make suggestions. – Caelian