這次給大家帶來Angular怎樣向組件輸入ngForOf,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" } ] }
效果就行這樣:
但是,我希望我們的puppiesListCmp元件可以滿足不同的需求,例如在資料不變的情況下只顯示小狗狗的name和color,就像這樣:
這就是本文的重點了。我們需要實作用戶自訂模板!
現在我們不寫死元件的範本了,而是讓使用者從外部輸入!
首先,我們的元件範本:
<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> ` })
效果就像這樣:
這樣的元件很靈活,想要什麼樣的效果都可以定制,這就實現了元件的復用。
相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!
推薦閱讀:
以上是Angular怎樣向組件輸入ngForOf的詳細內容。更多資訊請關注PHP中文網其他相關文章!