Search code examples
angularangular-ng-if

Angular show DIV only on some conditions


I have a header.component.html file (this is a shared component), in which I except other things added a DIV with a message. This should be shown only if showMsg property is true:

<div *ngIf="showMsg" >Some message</div>

In the header.ts file I defined the property

showMsg: boolean;

and in constructor default: this.showMsg= false;

This works fine, meaning if I set this.showMsg to true here, the message shows and vice versa.

But as this is a shared component, and it is included into main.html component via:

  <app-header></app-header>

and the data from backend, on which the showMsg should depend are only in main.ts component.

Only thing I need, let's say this.Year is a property from backend - and all I want is if the Year is 2021, then set showMsg to true and show message, otherwise hide the message in that shared component.

The problem is, my solution doesn't work:

if (this.Year === '2021')
      {this.showMsg = true; console.log(this.showMsg);}

Better to say, the condition is OK, showMsg will be set to true, but the message in header.html is not showing. Seems it ignores showMsg from main.ts.


Solution

  • Use @Input property in the child component to set it's value from the parent component.

    Child component controller

    import { Component, Input } from '@angular/core';
    
    @Component({...})
    export class SharedComponent {
      @Input() showMsg: boolean = false;  // <-- default when `[showMsg]` is not bound in parent
      ...
    }
    

    Parent component controller

    showMsg: boolean = false;
    
    someMethod() {
      this.someService.get('year').subscribe({
        next: (Year: any) => {
          this.showMsg = Year === '2021';
          ...
        },
        error: (error: any) => { }
      });
    }
    

    Parent component template

    <app-header [showMsg]="showMsg"></app-header>