Home > Back-end >  How to use event from child to parent
How to use event from child to parent

Time:10-01

I want to share totalJobsLength from child to parent. I get totalJobsLength from ChildComponent.component.ts on this function:

this.search.setup({
  .....
     };
     return this.service
       .searchJobs(projectid, payload)
       .pipe(
         tap(
           (page) =>
           (this.totalJobsLength = page.totalElements
           )
         ),
         map((page) => ({
 ....
         }))
       );
   }
 });

So my components hierarchy is:

ParentsComponent
--ChildComponent
       >ChildComponent.component.ts
       >ChildComponent.component.html
>ParentsComponent.component.ts
>ParentsComponent.component.html

I want to show totalJobsLength on ParentsComponent.component.html

 <p-tabPanel [header]="'All'">   //here I want to show `totalJobsLength`
        <ldd-child></ldd-child>
    </p-tabPanel>

Please can you share any idea how to implement?

CodePudding user response:

Child Component .ts

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

...........

this.search.setup({
  .....
     };
     return this.service
       .searchJobs(projectid, payload)
       .pipe(
         tap(
           (page) =>
           (this.totalJobsLength = page.totalElements;
            this.totalJobsLengthEvent.emit(page.totalElements);
           )
         ),
         map((page) => ({
 ....
         }))
       );
   }
 });

Parent Component .ts

onTotalJobsLength(value) =>{
  console.log('Total Jobs Length', value);
  this.totalJobsLengthParent= value;
}

Parent Component .html

<h1>Total Jobs Length - {{totalJobsLengthParent}} </h1>
 <p-tabPanel [header]="'All'">   //here I want to show `totalJobsLength`
        <ldd-child (totalJobsLengthEvent) = "onTotalJobsLength($event)"></ldd-child>
 </p-tabPanel>
  • Related