Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

115
Visualizações
Angular2 - ViewChild from a Directive

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);
  }
}
about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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);
  }
}
about 4 years ago · Santiago Trujillo Relatório

0

Since the component is not the child of the directive, the child selector will not work.

Instead, use references:

<my-easybox #myBox></my-easybox>
<p [myEasyBox]="myBox" data-href="URL">My Directive</p>
@Input('myEasyBox') myComponent: EasyBoxComponent;
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda