[英]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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.