Angular 2 component without selector tag in DOM

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...

Answers:

Answer

Use equivalent expanded *ngIf notation with template tag:

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

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>
Answer

You can solve this by using CSS only, just set my-component as display: contents,

    my-component {
        display: contents;
    }

As stated on display: contents documentation, this causes to appear as if the component were direct children of the element's parent.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.