Show component on button click from one component in angular 9

Viewed 4641

I have one "+" button in navbar which is inside

<app-navbar></app-navbar>

when i click on that i want to show component

<app-stepper></app-stepper>

This is my main parent app.component.html

  <app-navbar></app-navbar>
  <app-stepper></app-stepper>
  <app-test></app-test>
3 Answers

You could setup an event emitter in the app-navbar that emits when the + button is clicked. Then bind this event to an app-stepper show/hide toggler.

navbar.component.ts

export class NavbarComponent {
  @Output() onPlusClick = new EventEmitter<boolean>();

  plusClick() {
    ...
    this.onPlusClick.emit(true);
  }
}

navbar.component.html

<button (mouseup)="plusClick()">+</button>
...

app.component.ts

export class AppComponent {
  toggleStepper = false;
  ...
}

app.component.html

<app-navbar (onPlusClick)="toggleStepper = !toggleStepper"></app-navbar>
<app-stepper *ngIf="toggleStepper"></app-stepper>

Here I toggle the app-stepper everytime the + is clicked regardless of the event emitted by the onPlusClicked emitter. If you wish to bind the toggleStepper directly to the event emitted, you could do so by emitting the correct boolean in the navbar component and assigning it directly to the toggleStepper variable.

navbar.component.ts

plusClicked() {
  this.onPlusClicked.emit(true);
  // or `this.onPlusClicked.emit(false)` based on some condition 
}

app.component.html

<!-- here the `event$` is either `true` or `false` -->
<app-navbar (onPlusClick)="toggleStepper = $event"></app-navbar>
<app-stepper *ngIf="toggleStepper"></app-stepper>

You can create a shared service that is injected both into <app> and <app-navbar>

The Service would look somewhat like this:

@Injectable({
  providedIn: 'root',
})
export class SharedService{

  public showStepper: boolean = false;
}

It holds a boolean that says if the stepper should be shown or not.

Inside of <app-navbar>, when the user clicks the '+', set showStepper to true.

Next, inside of <app>, make a public property that returns the value of showStepper inside of the service like this:

public get showStepper(): boolean {
    return this._sharedService.showStepper;
    // _sharedService is the injected Service
}

And now inside of <app.component.html>, use the *ngIf directive to conditionally show your stepper component:

<app-stepper *ngIf="showStepper"></app-stepper>

You can achieve it as shown in this stackbliz.

You need to use an Output variable in the navbar component and emit a value on the + button click. In the app component, you need to watch for the event emitted by the navbar component and use that event value to show or hide the stepper component.

Related