dernor00
dernor00

Reputation: 271

Send values from one component to the other

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.

Upvotes: 0

Views: 69

Answers (1)

julianobrasil
julianobrasil

Reputation: 9377

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.

Upvotes: 1

Related Questions