Search code examples
javascriptangulartypescriptcomponentseventemitter

How to pass a boolean value between Angular components for switching display of a style


I have this form that is almost ready. Now I only have to make a modal window with content and it should pop open with click on a button which is inside of a child component. Modal, on the other hand, is a part of a parent component. I need to communicate them with each other in order to inform the parent, that the button was clicked and that now it's time to open a modal. I emit a boolean event, which is equal to the state of a clicked button, but I don't get any reaction from the parent, although I have a property bindable from outside (@Input()) How can I achieve such a task? Where am I mistaken?

Child component method

  onReset() {
    this.formResetClicked = !this.formResetClicked;

    this.formReseted.emit(this.formResetClicked); }

Parent's HTML

<div class="container">
  <div class="wrapper">
    <div class="slider">
        <app-form-slider class="slider-app"></app-form-slider>
    </div>
    <div class="form" (formReseted)="clickedState = $event">
        <router-outlet></router-outlet>
    </div>
    <div class="modal" [ngStyle]="{display: clickedState ? 'block' : 'none'}">
      <div class="modal__content">
        <div class="modal__content--header">
          <span>&times;</span>
          <p>WARNING!</p>
        </div>
        <div class="modal__content--text">
          <p>If you click 'continue' the all information will be deleted. <br>Close this window if you don't want this to happen.</p>
        </div>
        <div class="modal__content--button">
          <button>Continue</button>
        </div>
      </div>
    </div>
  </div>
</div>

Property of a parrent

export class AppComponent {
  title = 'AwesomeFormTask';

  @Input() clickedState: boolean;

}

Solution

  • Do not need to use @Input(). You can call child component to parent component using @Output() and EventEmitter as follows.

    child.component.ts

    @Output() formReseted = new EventEmitter<boolean>();
    
    formResetClicked: boolean = false;
    
    onReset() {
       this.formResetClicked = !this.formResetClicked;
       this.formReseted.emit(this.formResetClicked); 
    }
    

    Listen to formReseted event from the parent as follows.

    parent.component.html

    <child (formReseted)="testShowHide($event)"></child>
    
    <p *ngIf="show">Showing the Modal</p>
    

    parent.component.ts

    show: boolean = false;
    
      testShowHide(show) {
        this.show = show;
      }
    

    StackBlitz Demo