【问题标题】:Angular 2 component without selector tag in DOMDOM中没有选择器标签的Angular 2组件
【发布时间】:2016-11-12 05:40:50
【问题描述】:

我想要这个:

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

但我不想重复*ngIf,所以我用这个模板创建了我的组件&lt;my-component&gt;

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

我把 *ngIf 放在我的组件标签中:&lt;my-component *ngIf="..."&gt;

问题是 Angular 2 将 &lt;my-component&gt; 标记放入 DOM,我不想要它。

对于任何了解 ASP.NET WebForms 的人,我想要一个 Angular 2 中的组件,其工作方式类似于 &lt;asp:PlaceHolder&gt; 控件...

【问题讨论】:

  • 在 DOM 中放入输出意味着 有你不想拥有吗?
  • 没错,就是这样

标签: javascript angular angular2-template angular2-directives


【解决方案1】:

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

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

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

// becomes this in the dom

<div my-component _nghost...>

还有 ng-container 用于此目的。

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

// DOM: => <div class="here">Hello</div>

【讨论】:

    【解决方案2】:

    你可以只使用CSS来解决这个问题,只需将my-component设置为display: contents

        my-component {
            display: contents;
        }
    

    display: contentsdocumentation 所述,这会导致组件看起来好像是元素父级的直接子级。

    【讨论】:

      【解决方案3】:

      使用等效的expanded *ngIf 表示法和template 标签:

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

      【讨论】:

      • 是否有另一种方式来加载组件而无需在 DOM 中有选择器?我也需要这个,但我不认为我不能使用模板,因为我没有条件。有关信息,我想用 Angular2 生成复杂的 SVG。
      • 我也想看看这个框架是否可行。在很多用例中,您不希望组件标签仅显示在 DOM 中,而是显示该组件的内容。
      猜你喜欢
      • 2017-06-11
      • 2017-06-25
      • 1970-01-01
      • 2014-07-15
      • 2017-01-24
      • 2016-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多