Search code examples
javascripttwitter-bootstrapangularpaginationangular2-components

Angular 2 get dynamic value between components


I am using table plugin and pagination plugin. My target is to detect current page number from pagination component and to add it in table component. How is that possible? Already tried:

import { PaginationComponent } from '../+pagination/pagination.component';
@Component({
 ...
  providers: [PaginationComponent]
})
public currPage: number;
public constructor(private pagin: PaginationComponent) {
    this.currPage = this.pagin.page;
}

which works, but did not detect any changes. What must I change to make it detect changes?


Solution

  • When you're using it :

    <pagination (pageChanged)="pageChanged()"></pagination>
    

    Inside the class that uses above :

    export class SomethingThatUsesPagination{
        pageChanged($event){
            this.pageService.onChanged$.emit($event);
        }
    }
    

    and the create a service and inject it in both components

    @Injectable()
    export class PageService{
       public onChanged$ = new EventEmitter();
    }
    

    and then inside the other component that needs to know about pagination stuff :

    export class OtherComponent{
        constructpr(public pageService: PageService){
            pageService.onChanged$.subscribe(($event) => {
                console.log('$event',$event);
            });
        }
    }
    

    this is two component are communicating through a service.