Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

114
Views
Angular2 - ViewChild desde una directiva

Tengo un componente con el nombre EasyBoxComponent y una @Directive con este @Viewchild :

 @ViewChild(EasyBoxComponent) myComponent: EasyBoxComponent;

Pensé que esta era la sintaxis correcta, pero this.myComponent siempre está indefinido.


Aquí está el código completo:

 <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); } }
about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

ContentChild funciona con la interfaz AfterContentInit , por lo que la plantilla debería ser como:

 <p myEasyBox data-href="URL"> <my-easybox></my-easybox> </p>

y la @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); } }
about 4 years ago · Santiago Trujillo Report

0

Dado que el componente no es el elemento secundario de la directiva, el selector secundario no funcionará.

En su lugar, utilice referencias:

 <my-easybox #myBox></my-easybox> <p [myEasyBox]="myBox" data-href="URL">My Directive</p>
 @Input('myEasyBox') myComponent: EasyBoxComponent;
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!