user2065501
user2065501

Reputation: 99

Access custom directive with ViewChild / ContentChild

I've been trying to access my custom directive I applied on an element by using @ViewChild(CustomDirective) or @ContentChild(CustomDirective), respectively using the set variable for the first time in my ngAfterViewInit or ngAfterContentInit function.

However, neither of them worked. At first, I thought that it was due to me loading some content from a webserver, but even after having set static variables, it doesn't work.

Here's what I have:

@Directive({
  selector: '[det-insert]',
})
export class DetailedDirective {
  constructor(public viewContainerRef: ViewContainerRef) { }
}

And

... (importing + component stuff)
export class DetailedView implements AfterViewInit {
    @ViewChild(DetailedDirective) detView : DetailedDirective;
    constructor(...)
    ngAfterViewInit(){
        alert(detView);
    }
}

And the template:

<ng-template det-insert></ng-template>

However, the alert returns undefined.

And I have no clue as to why. Any ideas? I already looked through stackoverflow, but neither is my template obstructed by *ngIf, nor do I start using my queried directive before the proper "AfterXInit" function. I already tried switching ViewChild and AfterViewInit for ViewContent and AfterContentInit respectively, to no avail.

Upvotes: 1

Views: 1275

Answers (2)

Jake Smith
Jake Smith

Reputation: 2803

I ran into a similar issue myself. I created a separate module for various alert directives/components. My alert directive was defined and declared in that alert module. I was trying to use the directive in my app module, and in order to get this same example to work, you need to specify that the alert module exports: [AppLevelAlertDirective].

You can still use <ng-template yourDirective></ng-template>, despite it not showing up in the DOM later. This is captured well before the DOM is rendered. Please see https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html#!#loading-components

Upvotes: 2

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657058

Add DetailedDirective to declarations: [] of your module

<ng-template> isn't added to the DOM, and therefore DetailedDirective can't be found. If you use <div det-insert> it will work

Upvotes: 1

Related Questions