Akhil Sahu
Akhil Sahu

Reputation: 637

Access another component's from another component in angular 4

I need to scroll the tag in app.module.ts from another products component

app.module.ts

 <div  class="mdl-layout mdl-js-layout mdl-layout--fixed-header">
		<nav-header></nav-header>
 		<main class="mdl-layout__content" #scrollMe>
            <router-outlet></router-outlet>
						
		<app-footer [otherType]="'siteSetting'" [type]="'getAllPages'"></app-footer>
		</main>	
</div>  
	<cart-quantity-icon></cart-quantity-icon>

main tag i.e #scrollMe needs to be scrolled using following component

products.components.ts

import { Component, OnInit,ViewChild,ElementRef,ContentChild } from '@angular/core';
import { ActivatedRoute,   NavigationEnd ,Router, Event,  NavigationStart, RoutesRecognized,RouteConfigLoadStart, 
    RouteConfigLoadEnd,  NavigationCancel, NavigationError} from '@angular/router';
@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css']
})
	export class ProductsComponent implements OnInit {
 scrollTopButton = false;
  @ViewChild('infinite')  private myScrollContainer : ElementRef;
  @ContentChild('scrollMe')  private myScroll : ElementRef;
scrollToTop() {
    console.log(this.scrollTopButton);
     this.myScrollContainer.nativeElement.scrollTo(0, 0);
     this.myScroll.nativeElement.scrollTo(0, 0);

     window.scrollTo(0,0);
    //this.content.scrollToTop(700);
    this.scrollTopButton = false;
  }}
 <div style=" max-height: 750px;
      overflow: auto;" #infinite infiniteScroll
                                      [infiniteScrollDistance]="2"
                                      [infiniteScrollThrottle]="1000"
                                      (scrolled)="getProducts()" [scrollWindow]="false" class="mdl-grid mdl-cell mdl-cell--top mdl-cell--9-col mdl-cell--8-col-tablet mdl-cell--4-col-phone">

                              
                                   <!-- new card -->
                                   <product *ngFor="let p of products" [data]="p" [type]="'normal'"></product>

                                
                               		<div > 
									</div>
                          

<button *ngIf="scrollTopButton" (click)="scrollToTop()"   id="return-to-top" mat-fab color="primary"><i class="material-icons" style="font-size: 24px;">keyboard_arrow_up</i></button>

When I click the return-to-top button then I need to scroll #infinite and # scrollMe. I have tried following .Also instead of contentChild tried viewChild

 @ViewChild('infinite')  private myScrollContainer : ElementRef;
  @ContentChild('scrollMe')  private myScroll : ElementRef; //Also ViewChild here but none works!!
scrollToTop() {
    console.log(this.scrollTopButton);
     this.myScrollContainer.nativeElement.scrollTo(0, 0);
     this.myScroll.nativeElement.scrollTo(0, 0);

     window.scrollTo(0,0);
    //this.content.scrollToTop(700);
    this.scrollTopButton = false;
  }}

infinite works but scrollMe does not.

Upvotes: 0

Views: 2099

Answers (1)

ambussh
ambussh

Reputation: 790

This does not work because ContentChild from app-products does not have access to parent elements in DOM. You must use service for communication. ComService to create and and to provide.

import { Injectable, EventEmitter } from '@angular/core';
import { Observable, Subject } from 'rxjs';

@Injectable()
export class ComService {
   messageStream = new Subject();

   getMessageSubscribe() {
      return Observable.from(this.messageStream);
   }
   sendMessage() {
      this.messageStream.next(this.filteredOrderList);
   }
}

In component main component subscribe messages:

@ViewChild('scrollMe')  private myScroll : ElementRef;
constructor(
   private comService: ComService
) {
   this.subscribeMes = this.comService.getComunication().subsribe(element => {
    if(element) {
         this.myScroll.nativeElement.scrollTo(0, 0);
        //when element is true you got info from child to scroll 
    }
  })

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

}

And #scrollMe insert in top element in template of main component. In app-products:

constructor(
   private comService: ComService
) {}
@ViewChild('infinite')  private myScrollContainer : ElementRef;

scrollToTop() {
   console.log(this.scrollTopButton);
   this.myScrollContainer.nativeElement.scrollTo(0, 0);
   this.comService.sendMessage(true);

   window.scrollTo(0,0);
   //this.content.scrollToTop(700);
   this.scrollTopButton = false;
 }}

Upvotes: 1

Related Questions