Chrillewoodz Chrillewoodz - 2 months ago 9
TypeScript Question

Query for view variables inside directive not working

I have a directive:

@Directive({
selector: '[myDirective]'
})

export class MyDirective implements AfterViewInit {
@ViewChild('wrapper') wrapper;
@ViewChild('list') list;

ngAfterViewInit() {

// Both of these are undefined
console.log(wrapper, list);
}
}


Which needs to query for variables in the view that is it being used in.

So say I have this template in one of my components,
MyComponent
:

<div #wrapper myDirective>
<ul #list></ul>
</div>


It needs to find these variables, but the directive never manages to do this the way I have it now. My guess as to why this is happening is that since the directive doesn't actually have a view,
ngAfterViewInit
runs too soon and/or
@ViewChild
tries to find
wrapper
and
list
in the wrong place.

How can I make sure that the directive can find the variables?

Answer

Just change ViewChild to ContentChild. I suppose it should work

export class MyDirective implements AfterViewInit {
  @ContentChild('wrapper') wrapper;
  @ContentChild('list') list;

  ngAfterViewInit() {
    console.log(this.wrapper, this.list);
  }
}

Plunker Example