現在,我們寫一個組件puppiesListCmp,用於顯示小狗狗的列表: //puppies list.component.ts @Component({ selector: 'puppies list', template: ` {{puppy.name}} {{puppy.age}} {{pup ...
現在,我們寫一個組件puppiesListCmp,用於顯示小狗狗的列表:
//puppies-list.component.ts
@Component({
selector: 'puppies-list',
template: `
<div *ngFor="let puppy of puppies">
<span>{{puppy.name}}</span>
<span>{{puppy.age}}</span>
<span>{{puppy.color}}</span>
</div>
`
})
export class puppiesListCmp{
@Input() puppies: Puppy[];
}
interface Puppy {
name: string,
age: number,
color: string
}
然後這樣使用:
//app.component.ts
@Component({
selector: 'my-app',
template: `
<puppies-list [puppies]="puppies"></puppies-list>
`
})
export class App{
puppies = [
{
name: "sam",
age: 0.6,
color: "yellow"
},
{
name: "bingo",
age: 1.5,
color: "black"
}
]
}
效果就行這樣:
但是,我希望我們的puppiesListCmp組件可以滿足不同的需求,比如在數據不變的情況下只顯示小狗狗的name和color,就像這樣:
這就是本文的重點了。我們需要實現用戶自定義模板!
現在我們不寫死組件的模板了,而是讓用戶從外部輸入!
首先,我們的組件模板:
<div *ngFor="let puppy of puppies">
<span>{{puppy.name}}</span>
<span>{{puppy.age}}</span>
<span>{{puppy.color}}</span>
</div>
等價於:
<ng-template ngFor let-puppy [ngForOf]="puppies">
<div>
<span>{{puppy.name}}</span>
<span>{{puppy.age}}</span>
<span>{{puppy.color}}</span>
</div>
</ng-template>
然後,用@ContentChild(關於@ContentChild可以查看這裡,需FQ)獲取到外部(相對puppiesListCmp組件而言)自定義模板,並賦給ngForTemplate。也就是說,這部分:
<div>
<span>{{puppy.name}}</span>
<span>{{puppy.age}}</span>
<span>{{puppy.color}}</span>
</div>
不再像之前那樣寫死在組件里了,而是由使用者在父組件中自定義,然後利用Angular的內容投射(Content Projection),投射到puppiesListCmp組件裡面。就像這樣:
//puppies-list.component.ts
import { Component, Input, ContentChild, TemplateRef } from '@angular/core';
import { NgForOfContext } from '@angular/common';
@Component({
selector: 'puppies-list',
template: `
<ng-template ngFor let-puppy [ngForOf]="puppies" [ngForTemplate]="tpl"></ng-template>
`
})
export class puppiesListCmp{
@Input() puppies: Puppy[];
@ContentChild(TemplateRef) tpl: TemplateRef<NgForOfContext<Puppy>>
}
interface Puppy {
name: string,
age: number,
color: string
}
這樣我們的組件就算完成了。然後我們使用它:
//app.component.ts
@Component({
selector: 'my-app',
template: `
<puppies-list [puppies]="puppies">
<ng-template let-puppy>
<div>
<span>{{puppy.name}}</span>
<span>{{puppy.age}}</span>
<span>{{puppy.color}}</span>
</div>
</ng-template>
</puppies-list>
`
})
效果還是一樣的:
如果我們只要顯示小狗狗的name和color,只要這樣寫就好了:
//app.component.ts
@Component({
selector: 'my-app',
template: `
<puppies-list [puppies]="puppies">
<ng-template let-puppy>
<div>
<span>{{puppy.name}}</span>
<span>{{puppy.color}}</span>
</div>
</ng-template>
</puppies-list>
`
})
效果就像這樣:
這樣的組件很靈活,想要什麼樣的效果都可以定製,這就實現了組件的復用。
好了,本文就到此為止了。不當之處,歡迎指出!