Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

226
Vistas
How to pass an input to a directive that target a component

I have a directive that applies to every instances of a component (I use the component selector as the selector property of my directive), and I want to be able to pass input to that directive.

I made the example as small and compact as possible. Let's say I have a component that looks like this:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'component-a',
  template: `<h1>My format is {{ format }}!</h1>`
})
export class ComponentAComponent  {
  public format: string;
}

I have the following directive that targets and modify instances of this component:

import { Directive, Input } from '@angular/core';
import { ComponentAComponent } from './component-a.component';

@Directive({
  selector: 'component-a',
})
export class ComponentADirective {
  @Input() myCustomFormat;

  constructor(cmp: ComponentAComponent) {
    cmp.format = this.myCustomFormat;
  }
}

And I'm trying to pass it an input:

<component-a [myCustomFormat]="'Test'"></component-a>

However, it does not work. What am I doing wrong?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Directives follow the lifecycle of any Angular element.

This means that like components, an @Input is declared on specific hooks.

Instead of setting it in your constructor, try setting it either in

  • ngOnChanges
  • ngOnInit

Both are valid, but on init is triggered once, wherease on changes get triggered at every input vaue change.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda