Angular 2 component without selector tag in DOM

陌路散爱 提交于 2019-12-01 17:43:32

问题


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>


来源:https://stackoverflow.com/questions/38287224/angular-2-component-without-selector-tag-in-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!