Угловые директивы - как прослушивать выходные данные дочерних компонентов - PullRequest
0 голосов
/ 15 октября 2019

Как мой customDirective может прослушивать вывод clrDateChange в следующем примере?

<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>

Для обычных событий DOM я могу использовать elementRef.nativeElement.querySelector('input') для извлечения дочернего элемента ввода. Однако clrDateChange является угловым выходом.

Я хочу знать, возможно ли для директивы прослушивать выходы дочерних компонентов.

1 Ответ

1 голос
/ 15 октября 2019

Вы можете использовать переменную ссылки на шаблон.

@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>

РЕДАКТИРОВАТЬ

Только для подписки 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
  }

}
...