Home > Software design >  How to Call the method from one component to other components (individual components) in angular
How to Call the method from one component to other components (individual components) in angular

Time:07-13

I have an angular application n that I need to show the data based on the entered value in search field.

I am able to show the data in one component path is(components/platform/annotation-my-task/annotation-pm-admin-list)

pm-admin-list.component.ts

searchDetails(){
//here called the api and fetched the data
}

pm-admin-list.component.html

<div>
<input placeolder ="search here" [(ngModel)] ="search" (keyup.enter)="searchDetails()">
<img src="assets/imgs/search-icon">
</div>

<ul *ngFor ="let data of items">
<li>{{data.name}}</l>
<li>{data.status}}</li>
<li>{{data.lang}}</li>
</ul>

So from the above code when we enter some data to search and after entering it is working fine and showing the data as in list items above

But the same thing I need to show in other component and the path is (components/platform/annotation/annotation-process-list)

Both are non related components

My requirement is I need to show the same data as in first component(pm-admin-list.component.ts) in the other component (annotation-process-list)

I am very new to angular can anyone help me on the same

CodePudding user response:

You have to do

ng g s search

there will be a search.service.ts file generated similar to this

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class SearchService {
  
  constructor() { }
  //define the common function here
  searchDetails(){
  //here called the api and fetch the data
  }
}

then in the respective component in constructor you have to initialize the service and use the service for function call, in your case pm-admin-list.component.ts

constructor(private dataService: SearchService)

searchDetails(){
 SearchService.searchDetails()
}

This means the service is a common feature which can be called in any components and can be used multiple times. I don't know the logic in searchDetail function so I'm assuming(based on naming) it to return some values which can be used in that component locally

  • Related