Angular利用内容投射向组件输入ngForOf模板的方法
程序员文章站
2022-11-23 11:38:54
现在,我们写一个组件puppieslistcmp,用于显示小狗狗的列表:
//puppies-list.component.ts
@component({...
现在,我们写一个组件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> ` })
效果就像这样:
这样的组件很灵活,想要什么样的效果都可以定制,这就实现了组件的复用。
好了,本文就到此为止了。不当之处,欢迎指出!希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: 使用Angular CLI进行Build(构建)和Serve详解
下一篇: 好吃烤饼的做法,你做过吗