Angular DOM 中没有选择器标签的 2 个组件

Angular 2 component without selector tag in DOM

我想要这个:

<div *ngIf="...">div 1...</div>
<div *ngIf="...">div 2...</div>
<div *ngIf="...">div 3...</div>

但我不想重复 *ngIf,所以我用这个模板创建了我的组件 <my-component>

<div>div 1...</div>
<div>div 2...</div>
<div>div 3...</div>

然后我将 *ngIf 放在我的组件标签中:<my-component *ngIf="...">

问题是 Angular 2 将 <my-component> 标签放在 DOM 中,我不想要它。

对于了解 ASP.NET WebForms 的任何人,我想要 Angular 2 中的一个组件,其工作方式类似于 <asp:PlaceHolder> 控件...

template 标签使用等效的 expanded *ngIf 表示法:

<template [ngIf]="check">
  <div>div 1...</div>
  <div>div 2...</div>
  <div>div 3...</div>  
</template>

To answer your question, you can also do this...

@Component({
  selector: '[my-component]'...

<my-component *ngIf="..."</my-component>

// becomes this in the dom

<div my-component _nghost...>

There is also ng-container for this purpose.

<ng-container *ngIf="something.is.there">
  <div class="here">
    Hello
  </div>
</ng-container>

// DOM: => <div class="here">Hello</div>

你可以只用CSS解决这个问题,只需将my-component设置为display: contents

    my-component {
        display: contents;
    }

display: contents documentation 所述,这导致组件看起来好像是元素父元素的直接子元素。