Gaetitan
Gaetitan

Reputation: 324

How to use *ngIf on own selector of a component?

I have a component <my-component> that I want to only show if one of its properties is set. So I thought about doing something like this in <my-component>:

<ng-container *ngIf="myProperty">
    <div>...</div>
</ng-container>

The thing is the component is created in the HTML DOM. So, to avoid its creation, my assumption is that I should put the *ngIf on the selector of <my-component> in <parent-component>, which would make something like:

<parent-component>
    <my-component *ngIf="myProperty"></my-component>
</parent-component>

But in this case, the property myProperty would be set in <my-component> and not in <parent-component>.

So, if my assumption is correct, what is the way to implement that?

Upvotes: 2

Views: 2667

Answers (2)

TheViralGriffin
TheViralGriffin

Reputation: 451

Solution 1: The simples solution would be to wrap the contents of <my-component> (contents of my-component.component.html) in <ng-container> and adding *ngIf to it.

Solution 2: Create a service and in that service create a behaviour subject, inject the service in both the component, now you can toggle the value of that behaviour subject from <my-component> and listen in <parent-component> to toggle the <my-component>

Upvotes: 1

Marek W
Marek W

Reputation: 729

You already have your solution in your question. What you are doing with

<parent-component>
    <my-component *ngIf="myProperty"></my-component>
</parent-component>

is called content projection. And the content will not be projected, when you do not allow the rendering with *ngIf.

EDIT

As you forgot an important point, I have adapted my example in my StackBlitz. In order to do, what you want, you need to emit the flag from the inner component to the parent component via an EventEmitter. The parent component reacts to it and can therefore change the parameter to either hide or show the inner component.

StackBlitz example

Upvotes: 1

Related Questions