Karl Johan Vallner
Karl Johan Vallner

Reputation: 4310

Angular2 directive listen to parent component callbacks or changes

I have an angular2/4 directive that I made, that I attach to input DOM elements, which adds a class to them, marking that they are not empty.

@Directive({
    selector: '[inputNotEmptyAddClass]'
})
export class InputNotEmptyDirective implements OnInit {
...
@HostListener('change') onChange() {
        this.process();
    }
...
process() {
[Add class to parent input element, when it has a value]
}

It was all working fine, until I introduced a datepicker module (https://github.com/kekeh/mydatepicker) to the show. This module creates a new component, in which one of the children is an input and the whole thing lets me pick a date.

What I am trying to achieve here:

I want to rewrite my directive to listen in on either the date picker's callbacks or subscribe (I am using RXjS) to some of the datepickers variables. Yet I am out of ideas on how to implement this correctly.

What I have tried?

I have discovered that using the ControlValueAccessor

constructor( @Inject(NG_VALUE_ACCESSOR) private _valueAccessor: ControlValueAccessor )

I can check and see, if the element my directive is hooked into is the date picker.

if ( this._valueAccessor[0].constructor.name == 'MyDatePicker' ) {

Now I can see that it has onChange functions and all the variables, but I have no idea how to subscribe to them.

I could also use the modules callback functions in my directive, but they seem not to be triggering. Is there any way to make them trigger?

onDateChanged(event: IMyDateModel) {
        // event properties are: event.date, event.jsdate, event.formatted and event.epoc
    }

Bottom line.

I am open to any clues or solutions about how to hook a directive into the parent elements variables and callbacks. I understand that this is a pretty generic question, but maybe someone can point me in the right direction here.

Upvotes: 0

Views: 1282

Answers (1)

Vamshi
Vamshi

Reputation: 9331

You can listen to the event dispatched by the input . In case of date its dateChanged , in case of regular input its change .

Without the directive you can just say

<input type="text" (change)="doSomething()" />

// (dateChanged)="doSomething()" in case of date 

If you are having it in a directive, you can add HostListener to it.

@HostListener('dateChanged') dateChange() {
     //  do something  
}

Upvotes: 1

Related Questions