繁体   English   中英

渲染 <ng-content> 角度2次以上

[英]Rendering <ng-content> in angular 2 more times

我有这样的代码

<template *ngIf='mobile'>
  <div class='wrapper'>
    <div class='nav'>
        <ng-content></ng-content>
    </div>
  </div>
</template>

<template *ngIf='desktop'>
  <ng-content></ng-content>
</template>

但是,Angular 2只渲染了一次ng-content。 有没有办法让这个案子在没有太多黑客攻击的情况下正常工作?

更新Angular 5

ngOutletContext已重命名为ngTemplateOutletContext

另见https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29

原版的

您可以将内容作为模板传递,然后可以多次渲染它。

<parent>
 <template>
  projected content here
 </template>
</parent>

在父母

<ng-container *ngIf='mobile'>
  <div class='wrapper'>
    <div class='nav'>
        <template [ngTemplateOutlet]="templateRef"></template>
    </div>
  </div>
</ng-container>

<template *ngIf='desktop'>
  <template [ngTemplateOutlet]="templateRef"></template>
</template>

export class ParentComponent {
  constructor(private templateRef:TemplateRef){}
}

您还可以将数据传递到模板以与投影内容绑定。

<ng-container *ngIf='mobile'>
  <div class='wrapper'>
    <div class='nav'>
        <template [ngTemplateOutlet]="templateRef" [ntOutletContext]="{ $implicit: data}"></template>
    </div>
  </div>
</ng-container>

<ng-container *ngIf='desktop'>
  <template [ngTemplateOutlet]="templateRef" [ntOutletContext]="{ $implicit: data}"></template>
</ng-container>

export class ParentComponent {
  @Input() data;

  constructor(private templateRef:TemplateRef){}
}

然后像使用它一样

<parent [data]="data">
 <template let-item>
  projected content here {{item}}
 </template>
</parent>

另请参阅我自己的Angular 2 Table组件 - 双向数据绑定

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM