Home > database >  Angular 2 : Get Reference of appcomponent div in another components
Angular 2 : Get Reference of appcomponent div in another components

Time:06-08

I have components called app.component which is the main component in the angular project. Navigation to customer component is done by routing. And

Folder structer src\app

   - app.component.html
   - app.component.ts

and src\app\components\customer

  - customer.component.html
  - customer.component.ts

In my app.component.html

<div  #topContainerRef>
  <router-outlet></router-outlet>
</div>

In my customer.component.ts

I want to get reference of the top most container div which is contained in app.components

I want to replace

document.getElementsByClassName('top-container')[0].scrollTop = some values

with something similar to

@ViewChild('topContainerRef', { read: ElementRef, static: false }) topContainerRef: ElementRef;
    
this.topContainerRef.nativeElement.scrollTop= "some value" //here the topContainerRef is undefined

Is there any way i can use elementRef instead of classname or Id's.

CodePudding user response:

You cannot use ViewChild for the #topContainerRef to get a reference of this element, because it is not rendered by your CustomerComponent.

You either need to get the reference of this element inside the app component itself and find a way to pass it to all the other children that might need it (not recommended).

Or you can just build a service and use that to "request" the scrollTop change by whichever component has access to this element (in your case the app component).

I would do it something like this:

export class AppContainerService {
  private scrollTopSource = new ReplaySubject<number>(1);

  public scrollTop$ = this.scrollTopSource.asObservable();

  public updateScrollTop(value: number) {
    this.scrollTopSource.next(value);
  }
}

Inside your CustomerComponent:

public class CustomerComponent implements OnInit {
  // ...
  constructor(private containerService: AppContainerService) {
  }
  ngOnInit() {
    this.containerService.updateScrollTop(/* whatever value you need */);
  }
  // ...
}

And finally, the AppComponent that will react to the scrollTop changes:

export class AppComponent implements AfterViewInit {
  @ViewChild('topContainerRef', { read: ElementRef, static: false }) topContainerRef: ElementRef;
  private subscriptions = new Subscription();

  constructor(private containerService: AppContainerService) {
  }
  
  ngAfterViewInit() {
    this.subscriptions.add(this.containerService.scrollTop$.subscribe((value: number) => {
      this.topContainerRef.nativeElement.scrollTop = value;
    }));
  }

  ngOnDestroy() {
    this.subscriptions.unsubscribe();
  }
}

Don't forget about unsubscribing inside ngOnDestroy. This is important so that you don't have memory leaks

  • Related