本篇文章主要介紹了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>
<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> ` })
#效果就像這樣:
這樣的元件很靈活,想要什麼樣的效果都可以客製化,這就實現了元件的複用。
上面是我整理給大家的,希望今後會對大家有幫助。
相關文章:
Angularjs Promise實例詳解JS實作導出Excel的五種方法詳解#JavaScript實作寫入檔案到本機的方法#
以上是透過Angular利用內容投射向元件輸入ngForOf模板的方法步驟有哪些?的詳細內容。更多資訊請關注PHP中文網其他相關文章!