Passionate Coder
Passionate Coder

Reputation: 7294

How to pass template reference variables to child components

I am trying to apply scroll on specific elements in Angular. IU know how to do it and able to do it on but as I need to use it in many component I am trying to create a reusable component which will hold list of items.

On clicking to particular list I want to scroll to that div to particular element in parent but somehow I am not able to access template reference variable in parent.

How can I make it work? I have supplied a Stack Blitz:

https://stackblitz.com/edit/angular-mwwfwk

On clicking any item list in child I am getting below error

AppComponent.html:47 ERROR TypeError: el.scrollIntoView is not a function
    at AppComponent.scrollToItem (app.component.ts:26)
    at Object.eval [as handleEvent] (AppComponent.html:47)
    at handleEvent (view.ts:138)
    at callWithDebugContext (services.ts:630)
    at Object.debugHandleEvent [as handleEvent] (services.ts:377)
    at dispatchEvent (util.ts:135)
    at eval (provider.ts:156)
    at SafeSubscriber.schedulerFn [as _next] (event_emitter.ts:123)
    at SafeSubscriber.__tryOrUnsub (Subscriber.ts:265)

Upvotes: 1

Views: 1666

Answers (1)

JB Nizet
JB Nizet

Reputation: 691635

The objects you're passing to your scroll components have a name of type string, and a ref that is supposed to be an HTMLElement, but which is also a string. It must be an HTMLElement.

<scroll (clickedItem)="scroll($event)" [scrollItems]="[
 {name: 'Introduction', ref: introduction}, 
 {name: 'Content', ref: content}, 
 {name: 'Overview', ref: overview}]"></scroll>

See https://stackblitz.com/edit/angular-ahzef1?file=src%2Fapp%2Fapp.component.html for your fixed demo.

Upvotes: 3

Related Questions