Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access template reference inside a template element

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.

like image 290
Ashok Koyi Avatar asked Mar 01 '17 14:03

Ashok Koyi


People also ask

How do I pass a template reference variable in component?

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 .

What is true about template reference variables?

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.

How do I access ng template in component?

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 .

What does !: Means in Angular?

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.


2 Answers

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

like image 78
yurzui Avatar answered Sep 17 '22 18:09

yurzui


Try to look on lookedUpCustomElemRef inside ngAfterViewInit callback.

https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html

like image 26
Aleksandr Petrovskij Avatar answered Sep 21 '22 18:09

Aleksandr Petrovskij