本篇文章主要介紹了Angular利用內容投射向組件輸入ngForOf模板的方法,現在分享給大家,也給大家做個參考。
現在,我們寫一個元件puppiesListCmp,用來顯示小狗狗的清單:
#//puppies-list.component.ts @Component({ selector: 'puppies-list', template: ` <p *ngFor="let puppy of puppies"> <span>{{puppy.name}}</span> <span>{{puppy.age}}</span> <span>{{puppy.color}}</span> </p> ` }) 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" } ] }效果就行這樣:
#
<p *ngFor="let puppy of puppies"> <span>{{puppy.name}}</span> <span>{{puppy.age}}</span> <span>{{puppy.color}}</span> </p>等價於:
<ng-template ngFor let-puppy [ngForOf]="puppies"> <p> <span>{{puppy.name}}</span> <span>{{puppy.age}}</span> <span>{{puppy.color}}</span> </p> </ng-template>然後,用@ContentChild(關於@ContentChild可以查看這裡,需FQ )取得到外部(相對puppiesListCmp元件而言)自訂模板,並賦給ngForTemplate。也就是說,這部分:
<p> <span>{{puppy.name}}</span> <span>{{puppy.age}}</span> <span>{{puppy.color}}</span> </p>不再像之前那樣寫死在元件裡了,而是由使用者在父元件中自訂,然後利用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> <p> <span>{{puppy.name}}</span> <span>{{puppy.age}}</span> <span>{{puppy.color}}</span> </p> </ng-template> </puppies-list> ` })效果還是一樣的:
##如果我們只要顯示小狗狗的name和color,只要這樣寫就好了:
//app.component.ts @Component({ selector: 'my-app', template: ` <puppies-list [puppies]="puppies"> <ng-template let-puppy> <p> <span>{{puppy.name}}</span> <span>{{puppy.color}}</span> </p> </ng-template> </puppies-list> ` })
#效果就像這樣:
這樣的元件很靈活,想要什麼樣的效果都可以客製化,這就實現了元件的複用。
上面是我整理給大家的,希望今後會對大家有幫助。
相關文章:
Angularjs Promise實例詳解JS實作導出Excel的五種方法詳解#JavaScript實作寫入檔案到本機的方法#
以上是透過Angular利用內容投射向元件輸入ngForOf模板的方法步驟有哪些?的詳細內容。更多資訊請關注PHP中文網其他相關文章!