10

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.

2 Answers 2

9

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

Sign up to request clarification or add additional context in comments.

1 Comment

Looks like it is set right before ngAfterViewInit() is called. Thanks.
1

Try to look on lookedUpCustomElemRef inside ngAfterViewInit callback.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.