Home > database >  How to pass an input to a directive that target a component
How to pass an input to a directive that target a component

Time:06-08

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?

CodePudding user response:

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.

  • Related