Search code examples
javascriptangularangular-ng-if

How to hide/show component using ngif based on boolean from separate component


I'm trying to show/hide an element in a parent component when the user clicks on a button from the child component. I'm not sure if I'm doing something wrong or maybe I have the complete wrong approach

Parent Component

<div *ngIf="show">Hello World</div>
<div *ngIf="!show">Goodbye World</div>

Child Component

<button (click)="showHello()">
 <i class="fas fa-plus"></i>
</button>

Child Component .ts file

show: boolean = false;

showHello() {
    this.show = !this.show;
    console.log('show', this.show);
 }

Solution

  • parent:

    <hello #hello></hello>
    <p>
      {{hello.show}}
    </p>
    

    child:

    import { Component, Input } from '@angular/core';
    
    @Component({
      selector: 'hello',
      template: `<button (click)="showHello()">
                  Show
                  </button>`,
      styles: [`h1 { font-family: Lato; }`]
    })
    export class HelloComponent  {
      show: boolean = false;
    
      showHello() {
          this.show = !this.show;
          console.log('show', this.show);
      }
    }
    

    Live demo