Alex
Alex

Reputation: 143

Access a component method from another component in Angular 4

I have a dashboard component, a head component, and a userOverview component.

dashboard component .ts file

export class DashboardComponent implements OnInit {
    startTour() {
      // do something
    }
}

userOverview component .ts file

export class UserOverviewComponent implements OnInit {
    startTour() {
      // do something else
    }
}

header component .html file

<button (click)="openTour()"></button>

header component .ts file

export class HeaderComponent implements OnInit {
    openTour() {
                   // In here, I want to ask is there any way I could make a 
                   // call to  different component with the same method same.

      this.name = componentName // The component Name, such as
                                // DashboardComponent, UserOverviewComponent

      this.name.startTour(); // Something like this
    }
}

Now I am able to get this.name when navigate to different component, but I know by using this.name.startTour() is definitely not going to work.

Thanks for any hints or solutions.

Upvotes: 2

Views: 591

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222657

You cannot just call like that if the components are independent.If component1 and component2 are siblings you can use EventEmitter @Input

You can use also use a Shared service with subject. A service in Angular is a singleton, meaning it is managed as a single instance. So if each of the components access the service, they will access the same shared data.

Upvotes: 4

Related Questions