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

225
Views
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 answers
Answer question

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 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!