I'm using a library that expects me to specify body of a directive as a child of template element
<template customDirective>
   <custom-element #lookup></custom-element>
</template>
Is there a way to access custom-element#lookup inside my component.
For eg.,
@Component({
  selector: 'app-test',
  template: `
    <template customDirective>
       <custom-element #lookup></custom-element>
    </template>
  `
})
export class TestComponent {
  @ViewChild('lookup') viewChildRef;
  @ContentChild('lookup') contentChildRef;
  constructor() {
  }
  ngAfterContentInit(): void {
     console.log(this.viewChildRef); // <-- undefined
     console.log(this.contentChildRef); // <-- undefined
  }
}
I'm getting undefined in both cases.
To get started using template reference variables, simply create a new Angular component or visit an existing one. To create a template reference variable, locate the HTML element that you want to reference and then tag it like so: #myVarName .
A template reference variable is a feature that allows us to gain access to a part of our template. This could be an element, component, or could be a directive.
To access the above ng-template in the component or directive, first, we need to assign a template reference variable. #sayHelloTemplate is that variable in the code below. Now, we can use the ViewChild query to inject the sayHelloTemplate into our component as an instance of the class TemplateRef .
It's coercion to a boolean value. Means that you want to make sure your resulting value is either true or false, not undefined or [ ]. For example, you're passing the resulting value to something that expects a boolean and nothing else. This is how you coerce to a boolean type.
You cannot get reference to component inside template until you don't create embedded view.
Try using setter like:
@ViewChild('lookup') 
set lookUp(ref: any) {
  console.log(ref);
}
Plunker Example
Try to look on lookedUpCustomElemRef inside ngAfterViewInit callback.
https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With