angular - how to get a reference of a directive which has no exportAs

Viewed 1729

clrDate is a custom third party directive without an exportAs statement.

source code

@Directive({
  selector: '[clrDate]',
  host: {
    '[class.clr-input]': 'true',
  },
  providers: [DatepickerFocusService],
})
export class ClrDateInput extends WrappedFormControl<ClrDateContainer> implements OnInit, AfterViewInit, OnDestroy {
  @Input() placeholder: string;
  @Output('clrDateChange') dateChange: EventEmitter<Date> = new EventEmitter<Date>(false);
  @Input('clrDate')
...
}

I want to be able to get a reference to it from inside my controller as well as my customDirective. How can I do that?

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

Add #ref (template variable) on the directive and you can get it in the component

Depending on from where you want to access the directive instance, you should be able to get hands on it via @ViewChild or constructor injection.

From your controller (component) or from your customDirective you should be able to do following:

  // will be available in ngOnInit
  @ViewChild(ClrDateInput, { static: true })
  clrDateDirective: ClrDateInput;

assuming you can have multiple ClrDateInput directives you could use @ViewChildren:

  // will be available in ngAfterViewInit
  @ViewChildren(ClrDateInput)
  clrDateDirectives: QueryList<ClrDateInput>;

from the host element of the directive itself you can inject the directive via constructor injection:

// app.component.html
<custom-app ctrlDate></custom-app>

// custom-app.component.ts
@Component({
  selector: "custom-app",
  template: `
    <h2>Custom App</h2>
  `
})
class CustomAppComponent {
    constructor(@Self() private ClrDateInput: ClrDateInput) {}

You can take a look at a example sandbox.

Related