Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 786
lmcarreiro Avatar asked Jul 09 '16 23:07

lmcarreiro


People also ask

Can we use component without selector?

As you can see, in this view's @Component() meta-data, there is no "selector" property. With routable components, this isn't required. But, it can be used.

How do you render an Angular component without any wrapping tag?

To render a component without its wrapping tag with Angular, we can use attribute selectors. to set the selector of the component to '[myTd]' . to render the content of ChildComponent in the td element.

What is the role of the attribute selector in Angular component?

What is a Selector in Angular? A selector is one of the properties of the object that we use along with the component configuration. A selector is used to identify each component uniquely into the component tree, and it also defines how the current component is represented in the HTML DOM.

What is component in Angular?

Components are the main building block for Angular applications. Each component consists of: An HTML template that declares what renders on the page. A TypeScript class that defines behavior. A CSS selector that defines how the component is used in a template.


3 Answers

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>
like image 57
SoEzPz Avatar answered Oct 22 '22 21:10

SoEzPz


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.

like image 44
luiscla27 Avatar answered Oct 22 '22 20:10

luiscla27


Use equivalent expanded *ngIf notation with template tag:

<template [ngIf]="check">
  <div>div 1...</div>
  <div>div 2...</div>
  <div>div 3...</div>  
</template>
like image 24
dfsq Avatar answered Oct 22 '22 21:10

dfsq