How to not display subcomponent if it's empty without using *ngIf in it's parent?

Viewed 72

I have a following problem:

There is a Component A with a Subcomponent B.

<app-alert [response]="alertMessage"></app-alert>

Subcomponent B extends Ngb-alert component and has an template like:

<ngb-alert #selfClosingAlert id="selfClosingAlert" *ngIf="alertMessage" [type]="alertStyle" (closed)="alertMessage = ''">
  {{ alertMessage }}
</ngb-alert>

When the alertMessage is empty alert is hidden but my Subcomponent B tag still takes up some space on the site. Generally I want Subcomponent B to be self-responsible. I searched a lot for the answer but found nothing.

1 Answers

I solved it this way:

Added host class condition on my alertMessage value in Subcomponent B component decorator

@Component({
  selector: 'app-alert',
  templateUrl: './alert.component.html',
  styleUrls: ['./alert.component.css'],
  host: {
    '[class.d-none]': 'alertMessage === ""',
  }
})

So when alertMessage is empty, my Subcomponent B tag gets .d-none (bootstrap) class which sets it's display to 'none'. Now it doesn't take up any place when the alertMessage is empty.

Related