現在,我們寫一個組件puppiesListCmp,用於顯示小狗狗的列表:本文主要和大家介紹了Angular利用內容投射向組件輸入ngForOf模板的方法,希望能幫助到大家。
//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>
<p> <span>{{puppy.name}}</span> <span>{{puppy.age}}</span> <span>{{puppy.color}}</span> </p>
//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> ` })
效果就像這樣:
#### ##這樣的元件很靈活,想要什麼樣的效果都可以客製化,這就實現了元件的重複使用。 ###以上是Angular元件輸入ngForOf模板的方法實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!