0

I'm using angular material paginator: https://material.angular.io/components/paginator/examples The paginator triggers an event and I print the page size and a page index. I have this method in let say Component A.

 paginate($event: PageEvent) {
    concole.log($event.pageIndex);
    console.log($event.pageSize);  
  }

In Component B, I have two variables pIndex and pSize.

I want to assign these variables with values that I get from the PageEvent.

But the pageEvent happens in Component A.

I tried to add an event emitter in component A to emit the page size.

export class ComponentA {

    @Output() pageSizeEmitter = new EventEmitter<number>();

    paginate($event: PageEvent) {
      this.pageSizeEmitter.emit($event.pageSize);
      concole.log($event.pageIndex);
      console.log($event.pageSize);
    }
}

But then in Component B, I don't know how to assign it to the pSize variable.

export class ComponentB {

    pIndex: number =0; 
    pSize: number =?

}

I would very much appreciate any suggestion.

1 Answer 1

1

There are a few ways you can do that. One way is (maybe the simplest at the stage you are with your code - see the Stackblitz demo):

<component-b #compB></component-b>

<component-a (pageSizeEmitter)="compB.pSize = $event"></component-a>

Basically we are using template reference variables (compB in the code above).

You can improve that code significantly by calling a function and passing, as arguments, compB and $event and doing the rest on ts code.

And be warned that an *ngIf on <component-b> would ruin this solution. So, if I were you, I'd use more typescript code:

@ViewChild('compB') _compB: ComponentBComponent;

_setPageSize(pageSize: number) {this._compB.pSize = pageSize;}
<component-b #compB></component-b>

<component-a (pageSizeEmitter)="_setPageSize($event)"></component-a>

But, if I was doing it in production code, I'd do it using services, or, even better, using a complete state management solution, like ngrx.

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

2 Comments

can you make sample in stackbliz?
Of course. I'll put it in the answer. I simplified somethings two make it easier to build the stackblitz.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.