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);
}
}
ContentChild
works with the AfterContentInit
interface, so the template should be like:
<p myEasyBox data-href="URL">
<my-easybox></my-easybox>
</p>
and the @Directive
:
@Directive({
selector: '[myEasyBox]'
})
export class EasyBoxDirective implements AfterContentInit {
@ContentChild(EasyBoxComponent) myComponent: EasyBoxComponent;
@ContentChild(EasyBoxComponent) allMyCustomDirectives;
ngAfterContentInit(): void {
console.log('ngAfterContentInit');
console.log(this.myComponent);
}
constructor() {
}
@HostListener('click', ['$event'])
onClick(e) {
console.log(e);
console.log(e.altKey);
console.log(this.myComponent);
console.log(this.allMyCustomDirectives);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With