Angular 2 component without selector tag in DOM

2019-02-22 08:36发布

问题:

I want this:

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

But I don't wanna repeat the *ngIf, so I created my component <my-component>, with this template:

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

And I put *ngIf in my component tag: <my-component *ngIf="...">

The problem is that Angular 2 is putting the <my-component> tag in the DOM, and I don't want it.

For anyone who knows ASP.NET WebForms, I want a component in Angular 2 that works like <asp:PlaceHolder> control...

回答1:

Use equivalent expanded *ngIf notation with template tag:

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


回答2:

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>