主要內(nèi)容:
ng-content
ng-template
*ngTemplateOutlet
ng-container
1托嚣, 2 原文鏈接 Angular2 Tips & Tricks
3, 4 原文鏈接 Angular ng-template, ng-container and ngTemplateOutlet - The Complete Guide To Angular Templates
1. Content Projection (內(nèi)容投影)
Content Projection in Angular with ng-content 這篇文章講的比較詳細(xì)
使用 <ng-content></ng-content>
可以實現(xiàn)內(nèi)容投影,這個相當(dāng)于angular1.x中的 transclude
。這個還有一個 select
屬性馏锡,用來選擇投影的內(nèi)容哥桥。
內(nèi)容投影就是在組件內(nèi)部有1個或者多個槽點(slots)耍休。多用于Sections或Dialogs, 外部樣式固定蜓陌,內(nèi)部包含實際的內(nèi)容徐许。
// section.component.ts
@Component({
selector: 'app-section',
templateUrl: './section.component.html',
styleUrls: ['./section.component.css']
})
export class SectionComponent implements OnInit {
private visible: boolean = true; // 用來控制顯示或隱藏
constructor() { }
ngOnInit() {
}
}
// section.component.html
<div>
<h1>
<a href="#" (click)="visible = !visible">
<ng-content select="header"></ng-content> // 此處有個 'select' 屬性, 選擇 'header'
</a>
</h1>
<section *ngIf="visible">
<ng-content></ng-content> // 這里也有一個 ng-content
</section>
</div>
app.component中
// app.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
}
// app.component.html
<div>
<app-section> // 內(nèi)容投影
<header>hello</header>
<p>someone like you</p>
</app-section>
</div>
最后顯示效果如下
可以看出 有 select
屬性的就只顯示選擇的內(nèi)容丝里, 沒有改屬性的會顯示剩下的內(nèi)容曲初,而不是全部都顯示
ng-template 模板插件(template outlet)
ngTemplateOutlet
接受一個 模板引用 和一個上下文對象的模板插件,相當(dāng)于Angular1.x中的 ng-included
.也可以類比 router-outlet
,相當(dāng)于 其它模版的入口
// section.component.ts
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-section',
templateUrl: './section.component.html'
})
export class SectionComponent implements OnInit {
@Input() name: string; // 父組件傳入的上下文
@Input() template: any; // 父組件傳入的模板名稱
constructor() { }
ngOnInit() {
}
}
// section.component.html
<div>
<h1>Welcome</h1>
<ng-template // 這里插入其他的模板內(nèi)容
[ngTemplateOutlet]="template" // 模板名
[ngOutletContext]="{ name: name }" // 上下文對象
>
</ng-template>
</div>
父組件
// app.component.html
<div>
// 這個模板將被放在 子組件 <app-section>中
<ng-template let-name="name" #myTemplate> // let-name="name"為下上文名 '#myTemplate'問模板名
hi <strong>{{ name }}</strong> on {{ data.toLocaleString() }}
</ng-template>
<app-section
[name]="customer" // 上下文名
[template]="myTemplate" // 模板名
></app-section>
</div>
// app.component.ts
import { Component, Input, ViewChild } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
@ViewChild('myTemplate') myTemplate: any;
data: Date = new Date();
customer: string = 'James';
}
可以看出父組件中杯聚,對要插入的模板可以使用 let-name=name
創(chuàng)建模板的上下文對象名臼婆, #myTemplate
用來創(chuàng)建模板名。
子組件中需要引入動態(tài)的模板幌绍,可以使用 [ngTemplateOutlet]="outerTemplate"
來表示引入的外部模板名颁褂, 使用 [ngOutletContext]="{name: name}"
來表示下上文對象
最后顯示效果: