1

I have one stepper-component. Inside stepper-component.html, I have four components as the mat-steps like this -

<div class="container-fluid">
  <mat-horizontal-stepper linear #stepper>
    <mat-step label="Step1">
      <component-1></component-1>
    </mat-step>
    <mat-step label="Step2">
      <component-2></component-2>
    </mat-step>
    <mat-step label="Step3">
      <component-3></component-3>
    </mat-step>
    <mat-step label="Step4">
      <component-4></component-4>
    </mat-step>
  </mat-horizontal-stepper>
</div>

I want to access component2 from the click of a button in different component say componentX and execute some function in component2. How can I do that?

naveen
  • 53,448
  • 46
  • 161
  • 251
akash
  • 11
  • 1
  • You can use a singleton service and subjects to notify other components of something, but you should really thnk about why you have to have stepper components interfere with each other when they're supposed to be separate. –  Sep 18 '20 at 06:12
  • @MikeS. Actually I have two business requirements. I have to use steppers because the components are one big form. So to have a better user experience in terms of filling the forms. Second, I have one condition where if a user wants to edit any saved form later he can just use the button against a form tile in a different view and come to this second component in the stepper component. Now the problem is I'm not using any routing for the four components anywhere.I am just using the route for stepper-component. I just want to get to this second component somehow, maybe using it's index. – akash Sep 18 '20 at 07:51

1 Answers1

0

You can play with @Input() / @Output() or you can just import in your componentX the component2 and call the method. For example inside your componentX:

constructor(private component2: Component2) {}

clickMethod() {
    this.component2.method();
}
Lud
  • 286
  • 2
  • 10
  • **Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[Component2 -> Component 2-> Component2]: NullInjectorError: No provider for Component2!** .Getting this error in ComponentX in the constructor while declaring Component2 – akash Sep 18 '20 at 07:57
  • In your component add `providers`. ``` @Component({ templateUrl: "", styleUrls: [""], providers: [Component2] }) ``` – Lud Sep 18 '20 at 08:21