0

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?

2
  • What is the issue are you getting any error? Commented Jun 7, 2022 at 9:29
  • No error, it just does not pass the value, format is still undefined in the component Commented Jun 7, 2022 at 9:41

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.