Search code examples
angularangular-ngmodelangular-directive

Passing component to directive by input


I totally don't know what's going on.

I was trying write a simple directive to my custom component, which based on value (from ngModel) passing value to ther component (to ngModel too).

It's looks like that:

<form-text
    required
    birthDateExtracter="dateOfBirth"
    name="id"
    [(ngModel)]="model.idNumber"></form-text>

<form-datepicker #dateOfBirth
    name="Birth Date"
    [(ngModel)]="model.birthDate"></form-datepicker>

and my directive looks like:

@Directive({
  selector: '[ngModel][birthDateExtracter]'
})
export class BirthDateExtracterDirective {

  _component: any;

  @Input('birthDateExtracter')
  set birthDate(value: any) {
    this._component = value;
    console.log(value); //it's not working
  }

  constructor(private model: NgModel) {
  }

  @HostListener('ngModelChange', ['$event'])
  onModelChange(event) {
    console.log(event); //it works fine
  }
}

But instead of component to my Input was passing "dateOfBirth" string. I hope that's a silly, schollboy mistake or typo error, but I can't handle it. Or maybe I should make it in another way. Is there a mistake in this way?


Solution

  • Seems you forgot square brackets. I guess it should be:

    [birthDateExtracter]="dateOfBirth"
    

    or another way is using interpolation

    birthDateExtracter="{{dateOfBirth}}"