1

How can my customDirective listen to the clrDateChange output in the following example?

<clr-date-container customDirective>
    <label for="dateControl">Requirement Date</label>
    <input id="dateControl" type="date" [placeholder]="'TT.MM.YYYY'" [(clrDate)]="item.requirementDate" (clrDateChange)="onChange($event)" [ngModel]="null" name="requirementDate"/>
    <clr-control-error>{{ 'FORMS.VALIDATION.DATE_INVALID' | translate }}</clr-control-error>
</clr-date-container>

For normal DOM events I can use elementRef.nativeElement.querySelector('input') to retrieve the child input element. However clrDateChange is an angular output.

I want to know if it is generally possible for directive to listen to child component outputs.

Han Che
  • 8,239
  • 19
  • 70
  • 116

1 Answers1

1

You can use a template reference variable.

@Directive({
  selector: '[customDirective]',
  exportAs: 'CustomDirective'
})
export class CustomDirective {

  foo() {
    // do something
  }

}
<clr-date-container customDirective #myCustomDirective="CustomDirective">
  <label for="dateControl">Requirement Date</label>
  <input id="dateControl"
         type="date"
         [placeholder]="'TT.MM.YYYY'"
         [(clrDate)]="item.requirementDate"
         (clrDateChange)="onChange($event); myCustomDirective.foo()"
         [ngModel]="null"
         name="requirementDate"/>
  <clr-control-error>
    {{ 'FORMS.VALIDATION.DATE_INVALID' | translate }}
  </clr-control-error>
</clr-date-container>

EDIT

If only to subscription clrDate.clrDateChange.

import { Directive, ContentChild, AfterContentInit, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

import { ClrDateComponent } from '@clr/angular/*';

@Directive({
  selector: '[customDirective]',
  exportAs: 'CustomDirective'
})
export class CustomDirective implements AfterContentInit, OnDestroy {

  private destroy$ = new Subject();

  @ContentChild(ClrDateInput, {static: false}) clrDateComponent: ClrDateInput;

  ngAfterContentInit() {
    if (this.clrDateComponent) {
      this.clrDateComponent.clrDateChange
      .pipe(takeUntil(this.destroy$))
      .subscribe(data => {
        this.foo(data)
      })
    }
  }

  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }

  foo(data) {
    console.log(data);
    // do something
  }

}
Hsuan Lee
  • 2,300
  • 1
  • 10
  • 18