简体   繁体   English

如何在组件的自己的选择器上使用 *ngIf?

[英]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.我有一个组件<my-component> ,我只想显示它是否设置了其中一个属性。 So I thought about doing something like this in <my-component> :所以我想在<my-component>做这样的事情:

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

The thing is the component is created in the HTML DOM.事情是组件是在 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:因此,为了避免它的创建,我的假设是我应该将 * ngIf放在<parent-component><my-component>选择器上,这会产生类似的东西:

<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> .但在这种情况下,属性myProperty将设置在<my-component>而不是<parent-component>

So, if my assumption is correct, what is the way to implement that?那么,如果我的假设是正确的,那么实现它的方法是什么?

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 .当您不允许使用*ngIf进行渲染时,内容将不会被投影。

EDIT编辑

As you forgot an important point, I have adapted my example in my StackBlitz.由于您忘记了重要的一点,我在我的 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 .为了做到这一点,您需要通过EventEmitter将标志从内部组件发送到父组件。 The parent component reacts to it and can therefore change the parameter to either hide or show the inner component.父组件对其做出反应,因此可以更改参数以隐藏或显示内部组件。

StackBlitz example StackBlitz 示例

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.解决方案 1:最简单的解决方案是将<my-component>内容(my-component.component.html 的内容)包裹在<ng-container>并在其中添加*ngIf

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>解决方案 2:创建一个服务并在该服务中创建一个行为主体,在两个组件中注入该服务,现在您可以从<my-component>切换该行为主体的值并在<parent-component>侦听以切换<my-component>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM