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

lmc*_*iro 5 javascript angular2-directives angular2-template angular

我要这个:

<div *ngIf="...">div 1...</div>
<div *ngIf="...">div 2...</div>
<div *ngIf="...">div 3...</div>
Run Code Online (Sandbox Code Playgroud)

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

<div>div 1...</div>
<div>div 2...</div>
<div>div 3...</div>
Run Code Online (Sandbox Code Playgroud)

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

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

对于任何了解ASP.NET WebForms的人,我希望Angular 2中的一个组件像<asp:PlaceHolder>控件一样工作......

Lui*_*mas 7

您可以仅使用 CSS 来解决这个问题,只需设置my-componentdisplay: contents,

my-component {
    display: contents;
}
Run Code Online (Sandbox Code Playgroud)

display: contents 正如文档中所述,这会导致组件看起来像是元素父元素的直接子元素。


SoE*_*zPz 6

要回答你的问题,你也可以这样做......

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

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

// becomes this in the dom

<div my-component _nghost...>
Run Code Online (Sandbox Code Playgroud)

还有ng-container用于此目的。

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

// DOM: => <div class="here">Hello</div>
Run Code Online (Sandbox Code Playgroud)


dfs*_*fsq 4

使用带有标签的等效扩展*ngIf符号template

<template [ngIf]="check">
  <div>div 1...</div>
  <div>div 2...</div>
  <div>div 3...</div>  
</template>
Run Code Online (Sandbox Code Playgroud)