如何为NG-ZORRO中nzCard的[nzExtra]传递额外参数
解决NZ-Card的nzExtra模板传参问题
因为[nzExtra]直接绑定TemplateRef时,无法像ngTemplateOutlet那样传递上下文参数,你可以通过以下几种方式解决:
方式一:将模板放入循环内部
把ng-template放到*ngFor的循环体中,模板就能直接访问当前循环的choice和index变量:
<nz-card [nzHoverable]="true" *ngFor="let choice of choices; let i = index"> <ng-template #choiceaction> <!-- 直接使用循环变量 --> <button (click)="handleAction(choice, i)">操作{{i}}</button> </ng-template> <ng-container *nzCardExtra="choiceaction"></ng-container> </nz-card>
如果无需复用模板,也可以直接把内容写在*nzCardExtra指令里:
<nz-card [nzHoverable]="true" *ngFor="let choice of choices; let i = index"> <ng-container *nzCardExtra> <button (click)="handleAction(choice, i)">操作{{i}}</button> </ng-container> </nz-card>
方式二:封装组件传递参数
若模板逻辑复杂需要复用,可封装一个小组件,将choice和index作为输入参数:
- 创建组件文件:
// choice-action.component.ts import { Component, Input } from '@angular/core'; @Component({ selector: 'app-choice-action', template: ` <button (click)="handleClick()">操作{{index}}</button> ` }) export class ChoiceActionComponent { @Input() choice: any; @Input() index: number; handleClick() { // 直接使用组件输入的参数 console.log(this.choice, this.index); } }
- 在nz-card中引入使用:
<nz-card [nzHoverable]="true" *ngFor="let choice of choices; let i = index"> <ng-container *nzCardExtra> <app-choice-action [choice]="choice" [index]="i"></app-choice-action> </ng-container> </nz-card>
方式三:自定义指令实现模板传参(进阶)
自定义指令模拟ngTemplateOutletContext的功能,将参数传递给TemplateRef:
- 创建指令文件:
// template-with-context.directive.ts import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'; @Directive({ selector: '[appTemplateWithContext]' }) export class TemplateWithContextDirective { @Input() set appTemplateWithContext(context: any) { this.vcr.clear(); this.vcr.createEmbeddedView(this.templateRef, context); } constructor(private templateRef: TemplateRef<any>, private vcr: ViewContainerRef) { } }
- 在页面中使用该指令:
<ng-template #choiceaction let-choice="choice" let-index="index"> <button (click)="handleAction(choice, index)">操作{{index}}</button> </ng-template> <nz-card [nzHoverable]="true" *ngFor="let choice of choices; let i = index"> <ng-container *nzCardExtra> <ng-container [appTemplateWithContext]="{ choice: choice, index: i }" [ngTemplateOutlet]="choiceaction"></ng-container> </ng-container> </nz-card>
内容的提问来源于stack exchange,提问作者user3384985
相关产品推荐
相关产品推荐

